Sorting SQL by first two characters of fields

后端 未结 5 434
一生所求
一生所求 2021-01-18 08:01

I\'m trying to sort some data by sales person initials, and the sales rep field is 3 chars long, and is Firstname, Lastname and Account type. So, Bob Smith would be BS* and

5条回答
  •  清酒与你
    2021-01-18 08:42

    I hope that you never end up with two sales reps who happen to have the same initials.

    Also, sorting and filtering are two completely different things. You talk about sorting in the question title and first paragraph, but your question is about filtering. Since you can just ORDER BY on the field and it will use the first two characters anyway, I'll give you an answer for the filtering part.

    You don't mention your RDBMS, but this will work in any product:

    SELECT
         my_columns
    FROM
         My_Table
    WHERE
         sales_rep LIKE 'BS%'
    

    If you're using a variable/parameter then:

    SELECT
         my_columns
    FROM
         My_Table
    WHERE
         sales_rep LIKE @my_param + '%'
    

    You can also use:

    LEFT(sales_rep, 2) = 'BS'
    

    I would stay away from:

    SUBSTRING(sales_rep, 1, 2) = 'BS'
    

    Depending on your SQL engine, it might not be smart enough to realize that it can use an index on the last one.

提交回复
热议问题