0

This SQL for using some purpose but even i give a sort clause(order by tdate) still it is not sorting date wise. how to rewrite to get 'tdate' column sorted:

SELECT TOP 100 PERCENT * 
FROM   (SELECT TOP 100 PERCENT tdate, 
                               parti, 
                               Abs(Sum(amtdr)) AS Dr, 
                               Sum(amtcr)      AS Cr, 
                               nart 
        FROM   dbo.dbo_dayb a 
        WHERE  ( account = 'bank' ) 
        GROUP  BY idno, 
                  tdate, 
                  parti, 
                  nart 
        UNION ALL 
        SELECT tdate, 
               parti, 
               amtdr, 
               amtcr, 
               nart 
        FROM   dbo.dbo_dayb 
        WHERE  ( account = N'PDC account' ) 
               AND ( post = N'Cr' )) DERIVEDTBL 
ORDER  BY tdate 
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
Pravi
  • 9
  • 2

2 Answers2

0
 ((SELECT TOP 100 PERCENT * FROM 
 (SELECT TOP 100 PERCENT tdate, parti, 
 ABS(SUM(amtdr)) AS Dr, SUM(amtcr) AS Cr, nart FROM 
 dbo.dbo_dayb a 
 WHERE (account = 'bank') 
 GROUP BY idno, tdate, parti, nart) 

 UNION ALL 

 (SELECT tdate, parti, amtdr, amtcr, nart 
 FROM dbo.dbo_dayb 
 WHERE (account = N'PDC account') 
 AND (post = N'Cr')) DERIVEDTBL) )

 ORDER BY tdate

Try this

dhS
  • 3,739
  • 5
  • 26
  • 55
0

When returning data from views SQL may reorder you data even if you use an order by clause. One trick to get around this it to use ROW_NUMBER()

SELECT *, ROW_NUMBER() OVER (ORDER BY tdate) AS [ordinal]
FROM (SELECT tdate, parti, ABS(SUM(amtdr)) AS Dr, SUM(amtcr) AS Cr, nart
      FROM dbo.dbo_dayb a
      WHERE       (account = 'bank')
      GROUP BY idno, tdate, parti, nart
      UNION ALL
      SELECT      tdate, parti, amtdr, amtcr, nart
      FROM          dbo.dbo_dayb
      WHERE      (account = N'PDC account') AND (post = N'Cr')
) derived

As a note... the best way to get data out of a view in a particular order is to add an orderby to the query you are using to retrieve the data. (And that is the only way guaranteed to work)

Matthew Whited
  • 22,160
  • 4
  • 52
  • 69