Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting SQL by first two characters of fields

Tags:

sql

sorting

mysql

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 I just need to sort by the first two characters.

How can I pull all data for a certain rep, where the first two characters of the field equals BS?

like image 715
adam Avatar asked Nov 11 '09 16:11

adam


1 Answers

In some databases you can actually do

select * from SalesRep order by substring(SalesRepID, 1, 2)

Othere require you to

select *, Substring(SalesRepID, 1, 2) as foo from SalesRep order by foo

And in still others, you can't do it at all (but will have to sort your output in program code after you get it from the database).

Addition: If you actually want just the data for one sales rep, do as the others suggest. Otherwise, either you want to sort by the thing or maybe group by the thing.

like image 121
Rasmus Kaj Avatar answered Oct 14 '22 17:10

Rasmus Kaj