The ORDER BY clause is invalid in views, inline fu

2019-09-11 14:33发布

Error message

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.

Code:

SELECT * 
FROM 
    (SELECT 
         t.[Statement_ID], t.[InvoiceID], 
         t.S_Type as Type, t.Description, t.Date, 
         t.Debit, t.Credit, b.Balance 
     FROM 
         Statement as t 
     CROSS apply 
         (SELECT Balance = SUM(Debit) - SUM(Credit) 
          FROM Statement as x 
          WHERE (x.date < t.date or x.date = t.date and x.[Statement_ID] <= t.[Statement_ID] ) 
            AND x.CustID = t.CustID ) b 
     WHERE  
          t.CustID = '48' 
          AND date between '2015-01-01' AND '2016-01-01' 
     ORDER BY
         t.date) 
ORDER BY
    InvoiceID, Statement_ID

1条回答
霸刀☆藐视天下
2楼-- · 2019-09-11 15:15

Move first ORDER BY to the end:

SELECT * 
FROM 
    (SELECT 
         t.[Statement_ID], t.[InvoiceID], 
         t.S_Type as Type, t.Description, t.Date, 
         t.Debit, t.Credit, b.Balance 
     FROM 
         Statement as t 
     CROSS apply 
         (SELECT Balance = SUM(Debit) - SUM(Credit) 
          FROM Statement as x 
          WHERE (x.date < t.date or x.date = t.date and x.[Statement_ID] <= t.[Statement_ID] ) 
            AND x.CustID = t.CustID ) b 
     WHERE  
          t.CustID = '48' 
          AND date >= '2015-01-01' AND date <= '2016-01-01' 
         ) x
ORDER BY
    Date, InvoiceID, Statement_ID
查看更多
登录 后发表回答