动态订单条款包括计算列不起作用

时间:2014-09-29 21:07:46

标签: sql sql-server sql-server-2014

我有这样的陈述:

DECLARE @OrderBy nvarchar(50)
SELECT
    t1.Forename,
    t1.Surname,
/** Calculcated Column Start **/
    (
    SELECT
      (
      SELECT Count(FulfilledDelivery) FROM dbo.Deliveries d1 WHERE d1.UserID = t1.UserID
      )
      -
      (
      SELECT Count(CancelledDelivery) FROM dbo.Deliveries d1 WHERE d1.UserID = t1.UserID
      )
    ) AS 'Deliveries'
/** Calculcated Column End **/

FROM
    TableName t1
WHERE
ORDER BY 
    CASE WHEN @OrderBy = 'Deliveries' THEN 'Deliveries' END DESC,
    CASE WHEN @OrderBy = 'Forename' THEN t1.Forename END DESC,
    CASE WHEN @OrderBy = 'Surname' THEN t1.Surname END DESC
    END;

基本上,除了计算的列' Deliveries'在OrderBy子句中不起作用。我没有从我的SQL代码中获得任何错误,但它根本没有通过计算列来排序' Deliveries'当我将@OrderBy参数设置为" Deliveries"。

如果我删除动态order by子句,那么它可以正常工作:

.... 
ORDER BY 
   'Deliveries' DESC;

如何让它在动态版本中运行?

1 个答案:

答案 0 :(得分:1)

是别名不能按顺序访问,你可以使用CTE获取计算列的名称,或者你需要按顺序重复整个计算

;WITH CTE T
as
(
SELECT
    t1.Forename,
    t1.Surname,
/** Calculcated Column Start **/
    (
    SELECT
      (
      SELECT Count(FulfilledDelivery) FROM dbo.Deliveries d1 WHERE d1.UserID = t1.UserID
      )
      -
      (
      SELECT Count(CancelledDelivery) FROM dbo.Deliveries d1 WHERE d1.UserID = t1.UserID
      )
    ) AS 'Deliveries'
/** Calculcated Column End **/

FROM
    TableName t1
)
SELECT * FROM T
ORDER BY 
    CASE WHEN @OrderBy = 'Deliveries' THEN T.Deliveries END DESC,
    CASE WHEN @OrderBy = 'Forename' THEN T.Forename END DESC,
    CASE WHEN @OrderBy = 'Surname' THEN T.Surname END DESC
    END;