2

(使用 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 的场景相匹配。

4

2 回答 2

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;

您的表情计数(已交付)有点奇怪。只是为了确保它是您想要的:它将计算特定日期的已交付列中的值不为空的行数。

于 2012-05-04T14:14:33.663 回答
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
于 2012-05-04T14:19:04.630 回答