在具有子选择的查询的Sql Server表值表达式中排序

时间:2017-06-30 18:03:47

标签: sql sql-server tsql

我需要创建一个表值表达式,该表达式具有带子子选择和order by子句的查询。以下是表达方式。表达式内部的查询有效,但表达式给出了下面的错误。我尝试将TOP 100 PERCENT放在R_KEY前面,但这也会导致执行错误。为查询创建表值表达式的最佳方法是什么?我需要更改查询吗?

错误 Msg 1033,Level 15,State 1,Line 26 除非还指定了TOP,OFFSET或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效。

表值表达式

WITH BilledTotals as (
select R_KEY,                       -- Loan Number
       BILL_DATE,                   -- Bill Date
       BILLED_AMT,                  -- Bill Amount
       (SELECT SUM(b.BILLED_AMT)    -- Running Total for Billed Amount
        FROM temp_Billing_History b
        WHERE a.R_KEY = '47200100014871001   ' and a.R_KEY = b.R_KEY and b.BILL_DATE <= a.BILL_DATE) as RunningTotalBilled
from temp_Billing_History a where a.R_KEY = '47200100014871001   ' 
order by a.BILL_DATE
)

1 个答案:

答案 0 :(得分:1)

最好的方法是使用窗口函数:

WITH BilledTotals as (
      select R_KEY,                       -- Loan Number
             BILL_DATE,                   -- Bill Date
             BILLED_AMT,                  -- Bill Amount
             SUM(BILL_ED_AMT OVER (PARTITION BY a.R_KEY ORDER BY BILL_DATE) as  RunningTotalBilled
      from temp_Billing_History a
      where a.R_KEY = '47200100014871001   ' 
     )

通常,CTE中不需要order by。如果您希望订购最终结果,则最外层order by需要select