TSQL loop months in sequence(TSQL 循环月按顺序)
问题描述
我有一个问题,但我对此感到无法理解.
I have an query that I'm feeling out-of-my depth with.
我需要遍历两个日期之间的月份,并为每个月返回一个数据子集,并为没有数据的月份返回一个空白行.
I need to loop through months between two dates and return a subset of data for each month with a blank row for months with no data.
例如:
TransactionID | Date | Value
1 | 01/01/2015 | £10
2 | 16/01/2015 | £15
3 | 21/01/2015 | £5
4 | 15/03/2015 | £20
5 | 12/03/2015 | £15
6 | 23/04/2015 | £10
需要返回:
Month | Amount
January | £30
February | £0
March | £35
April | £10
我的查询将依赖于指定日期范围,以便我可以设置查询的第一个和最后一个日期.
My query will rely on specifying a date range so I can set the first and last date of the query.
我觉得我可能想多了,但已经到了那个阶段,你开始觉得自己束手无策.
I feel like I maybe over thinking this, but have gotten to that stage where you start to feel like you tying yourself in knots.
推荐答案
关键是可以访问一个整数列表来表示该范围内的月份.如果您没有 Numbers Table,则 spt_values 将在一点.
The key is having access to a list of integers to represent the months in the range. If you don't have a Numbers Table, then spt_values will do in a pinch.
SqlFiddle 演示
SELECT
[Year] = YEAR(DATEADD(month,[i],@range_start))
,[Month] = DATENAME(month,DATEADD(month,[i],@range_start))
,[Amount] = ISNULL(SUM([Value]),0)
FROM (
SELECT TOP (DATEDIFF(month,@range_start,@range_end)+1)
ROW_NUMBER() OVER(ORDER BY (SELECT 1))-1 [i]
FROM master.dbo.spt_values
) t1
LEFT JOIN #MyTable t2
ON (t1.[i] = DATEDIFF(month,@range_start,t2.[Date]) )
GROUP BY [i]
ORDER BY [i]
这篇关于TSQL 循环月按顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TSQL 循环月按顺序


- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01