SQL Server 2008:计算多个日期范围中的键数

时间:2010-01-18 16:50:58

标签: sql sql-server sql-server-2008

再次使用SQL Server 2008。我为每个ID设置了主键pt_id和日期时间列order_dts。我想计算1996 - 2008年每年的钥匙数量,并返回8个结果 - 每年计算一次。一年

SELECT COUNT pm.pt_id AS '1996'
FROM dm.medications pm
WHERE (pm.order_dts BETWEEN '1/1/1996' and '12/31/1996')

有效,但我怎么能这么做而不必像八个不同的查询那样做一些荒谬的事情?

谢谢!

2 个答案:

答案 0 :(得分:5)

SELECT COUNT(*),  Year(pm.order_dts) as Year
FROM dm.medications pm
WHERE Year(pm.order_dts) between 1996 AND 2008
group by Year(pm.order_dts)

如果你想要一行,你可以这样做:

SELECT 
    sum(case when Year(pm.order_dts) = 1996 then 1 end) as Count1996,
    sum(case when Year(pm.order_dts) = 1997 then 1 end) as Count1997,
    sum(case when Year(pm.order_dts) = 1998 then 1 end) as Count1998,
    sum(case when Year(pm.order_dts) = 1999 then 1 end) as Count1999,
    sum(case when Year(pm.order_dts) = 2000 then 1 end) as Count2000,
    sum(case when Year(pm.order_dts) = 2001 then 1 end) as Count2001,
    sum(case when Year(pm.order_dts) = 2002 then 1 end) as Count2002,
    sum(case when Year(pm.order_dts) = 2003 then 1 end) as Count2003,
    sum(case when Year(pm.order_dts) = 2004 then 1 end) as Count2004,
    sum(case when Year(pm.order_dts) = 2005 then 1 end) as Count2005,
    sum(case when Year(pm.order_dts) = 2006 then 1 end) as Count2006,
    sum(case when Year(pm.order_dts) = 2007 then 1 end) as Count2007,
    sum(case when Year(pm.order_dts) = 2008 then 1 end) as Count2008
FROM dm.medications pm

答案 1 :(得分:0)

select count(pm.pt_id) as count, datepart(yy, pm.order_dts) as year
from dm.medications pm
WHERE (pm.order_dts BETWEEN '1/1/1996' and '12/31/1996')
group by datepart(yy, pm.order_dts)