我该如何使用
ORDER BY
CASE @AccountOperator
WHEN '>' THEN AccountTrxValue
END ASC,
CASE @AccountOperator
WHEN '<' THEN AccountTrxValue
END DESC
当AccountTrxValue是别名并且是“select”中的以下结果时?
CASE WHEN PAA.RedeemValue>0 THEN
PAA.RedeemValue * -1
ELSE PAA.EarnValue END
AS AccountTrxValue ,
由于案例
,它不接受别名(不使用子查询)
所以有人回答我,我这样做了:
ORDER BY
CASE
WHEN @AccountOperator IS NULL OR @AccountOperator IN ('>','=') THEN
CASE WHEN PAA.RedeemValue>0 THEN
PAA.RedeemValue * -1
ELSE PAA.EarnValue END
END DESC,
CASE
WHEN @AccountOperator = '<'THEN
CASE WHEN PAA.RedeemValue>0 THEN
PAA.RedeemValue * -1
ELSE PAA.EarnValue END
END
如何以较短的方式书写? *我无法在“in”中包含null *我必须做2个案例,因为似乎“desc”应该写在“结束”之后
答案 0 :(得分:2)
ORDER BY
CASE @AccountOperator
WHEN '>' THEN AccountTrxValue
WHEN '<' THEN -AccountTrxValue
END
假设SQL Server
,您应该被允许在ORDER BY子句中使用列别名否则:
ORDER BY
CASE @AccountOperator
WHEN '>' THEN
CASE WHEN PAA.RedeemValue>0 THEN
PAA.RedeemValue * -1
ELSE PAA.EarnValue END
WHEN '<' THEN
-CASE WHEN PAA.RedeemValue>0 THEN
PAA.RedeemValue * -1
ELSE PAA.EarnValue END
END
编辑:
-AccountTrxValue或-CASE WHA PAA.RedeemValue&gt; 0 ...简单地否定该值。这意味着默认的ASC就像DESC ...
EDIT2: 非数字的一般情况
DECLARE @Switch char(1);
SELECT @Switch = '<';
SELECT
*,
ROW_NUMBER() OVER (ORDER BY SortCol ASC) AS SortASC,
ROW_NUMBER() OVER (ORDER BY SortCol DESC) AS SortDESC
FROM
dbo.tablename
ORDER BY
CASE @Switch
WHEN '<' THEN ROW_NUMBER() OVER (ORDER BY SortCol ASC)
WHEN '>' THEN ROW_NUMBER() OVER (ORDER BY SortCol DESC)
ELSE 0
END;