Link to home
Start Free TrialLog in
Avatar of Tsvetomir Tsanev
Tsvetomir Tsanev

asked on

MS SQL QUERY (Hard Query)

Hi I have 1 problem.
How I can write MS SQL query for given task:

ID   |    Name    |   Price    |
1     |   Gogo      |       5.00
2     |   Kiko        |     3.00
3     |  Ceco        |      5.00
4     |   Ceco       |      4.00
5     |  Bobo       |      3.00

How I can to ordered table like this:  Order By Name, Price  but name Ceco to be TOP and after that another Names to be ordered by ASK and his Price to ORdered ASK?????

ID   |    Name    |   Price    |
4     |   Ceco       |      4.00
3     |  Ceco        |      5.00
5     |  Bobo       |      3.00
1     |   Gogo      |       5.00
2     |   Kiko        |     3.00


PLEASE HELP ME
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hello,

You can try this

SELECT ID, Name, Price,CASE WHEN NAME='Ceco' THEN 1 ELSE 0 END RN
FROM YourTable
ORDER BY RN desc,Name, Price 

Open in new window

Avatar of Rgonzo1971
Rgonzo1971

Hi,

pls try

SELECT Table.ID, Table.Name, Table.Price
FROM Table
ORDER BY CASE WHEN NAME='Ceco' THEN Null ELSE NAME END, Table.Price;

Open in new window

Regards
Avatar of Tsvetomir Tsanev

ASKER

Thank you very much!
@Jim,

Well when I was writing my answer you had give a different answer.

And after my answer you have modified the logic as per my answer which has been awarded.

Anyways Nice job!
@Vitor - The only modification I made to my comment was to fix a typo which didn't alter any logic, make the CASE block bold, and then to add the SSMS testing code.
Its Ok Jim

You previous query was this

SELECT ID, Name, Price
FROM YourTable
ORDER BY CASE WHEN NAME='Ceco' THEN 1 ELSE 2 END, Ceco, Price 

Open in new window


Which is not correct.

But its very ok now.

Have a nice day
Correct, I changed Ceco to Name within two minutes of the original post, as I was developing the SSMS test code.