简体   繁体   中英

Order By in Sql Server Table Value Expression with Query That Has Sub-Select

I need to create a table value expression that has a query with a sub-select and order by clause. Below is the expression. The query inside of the expression works but, the expression gives me the error below. I tried placing TOP 100 PERCENT in front of R_KEY, but that also gives an execution error. What is the best way to create a table value expression for the query inside? Do I need to change the query?

Error Msg 1033, Level 15, State 1, Line 26 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

Table Value Expression

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
)

The best way is to use window functions:

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   ' 
     )

In general, an order by is unnecessary in the CTE. If you want the ultimate results to be ordered, you need an order by in the outermost select .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM