sort results by column not row

后端 未结 3 1164
长情又很酷
长情又很酷 2021-01-18 08:35

is it possible in SQL to sort by column and not by row? i do not need a basic ORDER BY statement, i know how those work (ie: order by column1, column2, etc).

basic

3条回答
  •  野的像风
    2021-01-18 09:03

    Are you using SELECT *? If so, stop doing that. If you know you want them listed that way, then write:

    SELECT [column 3], [column 1], [column 2] FROM dbo.table;
    

    If you mean you want to sort within those columns, I'm not sure how meaningful that would be. But I guess you could do something like:

    DECLARE @x TABLE(c1 INT, c2 INT, c3 INT);
    
    INSERT @x(c1,c2,c3) SELECT 2,1,3
    UNION ALL SELECT 3,4,5
    UNION ALL SELECT 5,4,3
    UNION ALL SELECT 3,1,2
    UNION ALL SELECT 3,3,3
    UNION ALL SELECT 3,4,3
    UNION ALL SELECT 4,3,4;
    
    SELECT c1 = CASE
      WHEN c1 >= c2 AND c1 >= c3 THEN c1
      WHEN c2 >= c1 AND c2 >= c3 THEN c2
      ELSE c3 END,
    c2 = CASE 
      WHEN c1 >= c2 AND c1 >= c3 THEN 
        CASE WHEN c2 >= c3 THEN c2 ELSE c3 END
      WHEN c2 >= c1 AND c2 >= c3 THEN
        CASE WHEN c1 >= c3 THEN c1 ELSE c3 END
      ELSE
        CASE WHEN c1 >= c2 THEN c1 ELSE c2 END
      END,
    c3 = CASE
      WHEN c1 <= c2 AND c1 <= c3 THEN c1
      WHEN c2 <= c1 AND c2 <= c3 THEN c2
      ELSE c3 END
    FROM @x;
    

    Results:

    c1   c2   c3
    ---- ---- ----
    3    2    1
    5    4    3
    5    4    3
    3    2    1
    3    3    3
    4    3    3
    4    4    3
    

提交回复
热议问题