SQL运行总计按日期分组

时间:2012-05-04 14:03:47

标签: sql-server-2008 count

(使用SQL Server 2008)如果我构建了一个视图,然后对视图进行查询,我可以轻松地将其工作,但我想在一个SQL查询中执行此操作。我有一个包含两列的表(DeliveredDate(DateTime),Delivered(Varchar))。我首先将DeliveredDate转换为Date,然后按Date分组。同时我正在执行Count on Delivered(列是YES或NULL)。以下是我用来完成这一部分的内容:

  SELECT CAST([DeliveredDate] As Date),
         COUNT([Delivered])
  FROM [TableName]
  GROUP BY CAST([DeliveredDate] As Date)
  ORDER BY CAST([DeliveredDate] As Date)

作为输出,我得到类似的东西:

DeliveredDate  |  Delivered
 2012-04-24          10
 2012-04-25         500
 2012-04-26         422
 2012-04-27          33

我正在寻找的是这样的:

DeliveredDate  |  Delivered  |  RunningTotal
 2012-04-24          10            10
 2012-04-25         500           510
 2012-04-26         422           932
 2012-04-27          33           965

我已经尝试过各种我见过的例子,但似乎没有一个与在Count上执行Count和RunningTotal的情况相匹配。

2 个答案:

答案 0 :(得分:3)

如果您使用的产品为SUM实现了有序的OVER子句,您可以执行以下操作:

select
  cast(DeliveredDate as date) as DeliveredDate,
  count(Delivered) as Delivered,
  sum(count(Delivered)) over (
    order by DeliveredDate
  ) as RunningTotal
from Orders
group by OrderDate
order by OrderDate;

你的表达计数(Delivered)有点奇怪。只是为了确定它是你想要的:它将计算特定日期的行数,其中Delivered列中的值为NOT NULL。

答案 1 :(得分:1)

我不确定CTE是否算作视图,但这将在SQL 2005+中起作用,它不支持SUM的有序OVER子句,

WITH cte (DeliveredDate, Delivered)
     AS (SELECT Cast([DeliveredDate] AS DATE) DeliveredDate, 
                Count([Delivered]) Delivered 
         FROM   [TableName] 
         GROUP  BY Cast([DeliveredDate] AS DATE)) 
SELECT d1.delivereddate, 
       d1.delivered, 
       Sum(d2.Delivered) RunningTotal 
FROM   cte d1 
       LEFT JOIN cte d2 
         ON d1.delivereddate >= d2.DeliveredDate 
GROUP  BY d1.delivereddate, 
          d1.delivered 
ORDER BY d1.delivereddate