SQL Server,使用变量排序

时间:2017-10-30 20:52:20

标签: sql sql-server tsql

我知道我必须使用案例才能使用变量,但我怎样才能创建一个包含方向的变量(ascdesc),最好使用if / else或类似的东西

为此,我有一个名为@orderDirection的变量。哪个可以有ascdesc作为值。

ORDER BY
    CASE WHEN @order = 1 THEN [date_time] END,
    CASE WHEN @order = 2 THEN [company] END,
    CASE WHEN @order = 3 THEN [country_1] END,
    CASE WHEN @order = 4 THEN [country_2] END,
    [date_time]

我想将其他内容包括在内,所以如果它不是desc那么它应该总是按升序排列,即使这个值完全不同。

这样的事情:

IF @orderDirection = 'desc' THEN
    ORDER BY
        CASE WHEN @order = 1 THEN [date_time] END desc,
        CASE WHEN @order = 2 THEN [company] END desc,
        CASE WHEN @order = 3 THEN [country_1] END desc,
        CASE WHEN @order = 4 THEN [country_2] END desc,
        [date_time]
ELSE
    ORDER BY
        CASE WHEN @order = 1 THEN [date_time] END asc,
        CASE WHEN @order = 2 THEN [company] END asc,
        CASE WHEN @order = 3 THEN [country_1] END asc,
        CASE WHEN @order = 4 THEN [country_2] END asc,
        [date_time]

2 个答案:

答案 0 :(得分:1)

您可以使用动态SQL执行此操作。但是使用常规SQL,列出每个选项:

ORDER BY (CASE WHEN @order = 1 AND @orderDirection = 'desc' THEN [date_time] END ) desc,
         (CASE WHEN @order = 2 AND @orderDirection = 'desc' THEN [company] END) desc,
         (CASE WHEN @order = 3 AND @orderDirection = 'desc' THEN [country_1] END) desc,
         (CASE WHEN @order = 4 AND @orderDirection = 'desc' THEN [country_2] END) desc,
         (CASE WHEN @order = 1 AND @orderDirection = 'asc' THEN [date_time] END ),
         (CASE WHEN @order = 2 AND @orderDirection = 'asc' THEN [company] END),
         (CASE WHEN @order = 3 AND @orderDirection = 'asc' THEN [country_1] END),
         (CASE WHEN @order = 4 AND @orderDirection = 'asc' THEN [country_2] END),
         [date_time]

答案 1 :(得分:0)

将您的查询放入CTE并创建一个整数ID字段,然后按该字段顺序或负面排序:

declare @orderDirection varchar(4) = 'asc'
,@order int = 1

;with a as(
select ROW_NUMBER() OVER (ORDER BY 
                         CASE WHEN @order = 1 THEN [date_time] END,
                         CASE WHEN @order = 2 THEN [company] END,
                         CASE WHEN @order = 3 THEN [country_1] END,
                         CASE WHEN @order = 4 THEN [country_2] END,
                         [date_time]
                         ) AS ID
...    --other fields
FROM [table]
)

SELECT
*
FROM a
ORDER BY (ID * case when @orderDirection = 'asc' then 1 else -1 end)