question

RSuabshini avatar image
RSuabshini asked

MS SQL - Sorting the values

The input and the (needed) desired output is shown below. It is in the form of Image ![alt text][1] [1]: /storage/temp/4280-1.png The code is select *from k order by case when Msg = ‘a1’ or Msg = ‘b1’ or Msg = ‘b0’ or Msg = ‘c’ or Msg = ‘d1’ or Msg = ‘e1’ or Msg = ‘f1’ or Msg = ‘g’ or Msg = ‘h’ or Msg = ‘i’ then 1 when Msg = ‘p0’ then 2 when Msg = ‘p1’ then 3 when Msg = ‘qq’ then 4 when Msg = ‘i’ then 5 when Msg = ‘j’ then 6 when Msg = ‘k0’ then 7 when Msg = ‘k1’ then 8 when Msg = ‘l’ then 9 when Msg = ‘l1’ then 10 else 11 end,Msg But this code is not giving the desired output. In case if there is only one set of values in the ‘id’ column then it sorts the ‘Msg’ column accordingly as per the condition given in the code. But in the sample input there are 3 different sets of values in ‘id’ column (1,2 and 3). So when I execute the above code the sorting is done for the whole data. It is obvious because I did not give any conditions for grouping by ‘id’ column. Is there any solution to achieve the desired result? (Also I tried to fetch each line in the input table by using cursors but even there I was not able to put the conditions properly in the loop). Any help would be useful
tsqlmssql2008
1.png (10.8 KiB)
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

KenJ avatar image KenJ commented ·
can you supply the desired output? I'm not sure how you want the results to look.
0 Likes 0 ·

1 Answer

·
Oleg avatar image
Oleg answered
I am not sure why you did not include the id column as the first column in the order by clause, it should do the trick: select * from k order by id, case when Msg in ('a1', 'b1', 'b0', 'c', 'd1', 'e1', 'f1', 'g', 'h', 'i' then 1 when Msg = 'p0' then 2 when Msg = 'p1' then 3 when Msg = 'qq' then 4 when Msg = 'i' then 5 when Msg = 'j' then 6 when Msg = 'k0' then 7 when Msg = 'k1' then 8 when Msg = 'l' then 9 when Msg = 'l1' then 10 else 11 end, Msg Please note that there is a bug in the case statement: you list **Msg = 'i'** for value 1 and then you repeat it with **when Msg = 'i' then 5**. The latter will never happen because the case statements' conditions are evaluated left to right then top to bottom. Hope this helps. Oleg
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.