SQL运行总计按日期分组

编程入门 行业动态 更新时间:2024-10-27 02:26:37
本文介绍了SQL运行总计按日期分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

(使用SQL Server 2008)我可以很容易地得到这个工作,如果我建立一个视图,然后查询视图,但我想在一个SQL查询中执行此。我有一个表,其中包含两列(DeliveredDate(DateTime),Delivered(Varchar))。我首先将DeliveredDate转换为仅日期,然后按日期分组。同时,我执行计数交货(列是YES或NULL)。这是我用来完成这部分:

(Using SQL Server 2008) I could easily get this to work if I built a view, and then a query on the view, but I want to perform this in one SQL query. I have a table that contains two columns (DeliveredDate (DateTime), Delivered (Varchar)). I am first converting DeliveredDate to Date only, and then grouping by Date. At the same time I am performing a Count on Delivered (column is either YES or NULL). Here is what I use to accomplish this portion:

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

作为输出,我会得到类似的结果:

As an output, I get something like:

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和

I've tried various examples I've seen out there, but none seem to match this scenario of performing a Count and a RunningTotal on said Count.

推荐答案

我不确定CTE是否计为一个视图,但这将在SQL 2005+它不支持SUM的有序OVER子句,

I'm not sure if a CTE counts as a view but this will work in SQL 2005+ which Does Not Support ordered OVER clauses for SUM,

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

更多推荐

SQL运行总计按日期分组

本文发布于:2023-10-30 22:21:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544171.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按日   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!