how to order 2 SQL Fields in asc and desc dynamically

后端 未结 4 1519
夕颜
夕颜 2021-01-18 22:46

I want to Order a SQL Select Query where there\'s 2 fields that are in the order by. I then need to decide if one is Descending and the other as Ascending. How is this done<

4条回答
  •  花落未央
    2021-01-18 23:40

    SELECT 
      Customer_ID,                        
      Name,                               
      Age                                         
    FROM
      #Customer
    ORDER BY 
      CASE WHEN @field = 'Name' AND @direction = 'A' THEN Name ELSE NULL END ASC,
      CASE WHEN @field = 'Name' AND @direction = 'D' THEN Name ELSE NULL END DESC,
      CASE WHEN @field = 'Age'  AND @direction = 'A' THEN Age  ELSE NULL END ASC,
      CASE WHEN @field = 'Age'  AND @direction = 'D' THEN Age  ELSE NULL END DESC
    


    I wouldn't want to do that over many different combinations though. If you have a lot of combinations I'd do somethign based on the following...

    SELECT 
      Customer_ID,                        
      Name,                               
      Age                                         
    FROM
    (
      SELECT
        Customer_ID,
        Name,
        ROW_NUMBER() OVER (ORDER BY Name) AS "name_order",
        Age,
        ROW_NUMBER() OVER (ORDER BY Age)  AS "age_order"
      FROM
        #Customer
    )
      AS [data]
    ORDER BY 
      CASE @field1
        WHEN 'Name' THEN CASE @direction1 WHEN 'A' THEN name_order ELSE -name_order END
        WHEN 'Age'  THEN CASE @direction1 WHEN 'A' THEN age_order  ELSE -age_order  END
        ELSE NULL
      END,
      CASE @field2
        WHEN 'Name' THEN CASE @direction2 WHEN 'A' THEN name_order ELSE -name_order END
        WHEN 'Age'  THEN CASE @direction2 WHEN 'A' THEN age_order  ELSE -age_order  END
        ELSE NULL
      END
    

    Repeat as many times as is required...


    Note: Just because it can be done this way, doesn't mean it should be done this way.

提交回复
热议问题