我有一张桌子,下面是一个例子,列出了人们及其出生和死亡年份(9999表示活着的人)。
person | born | died
1 | 2001 | 9999
2 | 2002 | 2003
3 | 2002 | 2008
4 | 2004 | 2009
5 | 2005 | 9999
6 | 2010 | 2012
我想计算多年来的人口。对于上面显示的示例,输出将如下所示。行末尾的活动人员列表仅供演示之用,我的输出中不需要。
year | population
2001 | 1 (1)
2002 | 3 (1,2,3)
2003 | 2 (1,3)
2004 | 3 (1,3,4)
2005 | 4 (1,3,4,5)
2006 | 4 (1,3,4,5)
2007 | 4 (1,3,4,5)
2008 | 3 (1,4,5)
2009 | 2 (1,5)
2010 | 3 (1,5,6)
2011 | 3 (1,5,6)
2012 | 2 (1,5)
我能够编写一个C#程序并循环遍历原始表中的每一行,并递增出生年和死亡年之间每年的人口数。但是,我需要完全在TSQL脚本中完成它。我是TSQL的新手。我该怎么办呢?如果已经讨论过类似的问题,请指出。谢谢。
答案 0 :(得分:1)
DECLARE @t TABLE(person INT, born INT, died INT);
INSERT @t VALUES
(1,2001,9999),
(2,2002,2003),
(3,2002,2008),
(4,2004,2009),
(5,2005,9999),
(6,2010,2012);
DECLARE @start INT, @end INT;
SELECT @start = 2001, @end = 2012;
;WITH n(y) AS
(
SELECT TOP (@end - @start + 1)
@start - 1 + ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_objects
)
SELECT
[year] = n.y,
population = SUM(CASE WHEN n.y >= t.born AND n.y < t.died THEN 1 ELSE 0 END)
FROM n CROSS JOIN @t AS t GROUP BY n.y;
结果:
year population
---- ----
2001 1
2002 3
2003 2
2004 3
2005 4
2006 4
2007 4
2008 3
2009 2
2010 3
2011 3
2012 2
FWIW我刚开始撰写关于此事的博客系列:
http://www.sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1