how to order 2 SQL Fields in asc and desc dynamically

后端 未结 4 1636
夕颜
夕颜 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:42

    In SQL Server 2005+ you could employ the following device:

    WITH CustomerCTE AS (
      SELECT
        *,
        DateSort = ROW_NUMBER() OVER (ORDER BY Date),
        NameSort = ROW_NUMBER() OVER (ORDER BY Name)
      FROM Customer
    )
    SELECT *
    FROM CustomerCTE
    ORDER BY DateSort * @DateSortDir, NameSort * @NameSortDir
    

    The vars in this case should be either 1 or -1.


    EDIT

    The additionally posted example seems to imply that the order of columns to use in ORDER BY should be dynamical too. And it also now seems that the order direction is specified uniformly for both columns.

    Whether it is so or not (the question has become a bit more ambiguous), both are assumed in my second solution.

    DECLARE @IntSortDir int;
    SET @IntSortDir = CASE @directionOfSort WHEN 'A' THEN 1 ELSE -1 END;
    
    WITH CustomerCTE AS (
      SELECT
        Customer_ID,
        Name,
        Age,
        NameSort = ROW_NUMBER() OVER (ORDER BY Name),
        AgeSort  = ROW_NUMBER() OVER (ORDER BY Date)
      FROM Customer
    )
    SELECT
      Customer_ID,
      Name,
      Age
    FROM CustomerCTE
    ORDER BY
      CASE @fieldSort WHEN 'Age' THEN AgeSort END * @IntSortDir,
      NameSort * @directionOfSort,
      CASE @fieldSort WHEN 'Name' THEN AgeSort END * @IntSortDir
    

    @fieldSort specifies the primary order column. The other one automatically becomes the secondary one.

提交回复
热议问题