联合排序都不成功

时间:2016-09-04 08:54:01

标签: sql-server

这个SQL用于某些目的,但即使我给出一个排序子句(按tdate排序)仍然没有明确排序日期。如何重写以获得' tdate'列已排序:

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 

2 个答案:

答案 0 :(得分:0)

warning

试试这个

答案 1 :(得分:0)

从视图返回数据时,即使您使用order by子句,SQL也可能会重新排序数据。解决这个问题的一个技巧是使用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

作为注释......以特定顺序从视图中获取数据的最佳方法是向用于检索数据的查询添加orderby。 (这是保证工作的唯一方式)