1

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
Amit Raj
  • 1,358
  • 3
  • 22
  • 47
Ayman
  • 842
  • 6
  • 16
  • 31

1 Answers1

0

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
Petrik
  • 823
  • 2
  • 12
  • 25
  • 1
    You need an alias for a subquery in `FROM`. This will currently error with "incorrect syntax near `ORDER BY`..." or words to that effect. `t` would be a suitable one and would make the reference to `t` in the `ORDER BY` valid again also (there's no `t` alias visible in the outer query, currently). – Damien_The_Unbeliever Jan 07 '16 at 13:37
  • Cough. You've made half of the correction I suggested. Re-read the third sentence in the previous comment. `t.date` is still going to cause issues as this currently stands. – Damien_The_Unbeliever Jan 07 '16 at 13:48
  • Sorry, I haven't realised that it is refering to alias, which obviously won't be valid in outer query. Now the ORDER BY is using the column name, so will work fine. I have also changed the BETWEEN to >= AND <= (Please read: https://sqlblog.org/2011/10/19/what-do-between-and-the-devil-have-in-common ) – Petrik Jan 07 '16 at 13:54
  • Also if Date is in Datetime format, please explicitly convert or cast this to DATE datatype – Petrik Jan 07 '16 at 13:55
  • 1
    thanks Petrik for the solution – Ayman Jan 07 '16 at 14:33