开发者

SQL Server 2008: Count Number of Keys In Multiple Date Ranges

开发者 https://www.devze.com 2022-12-17 05:48 出处:网络
SQL Server 2008 again. I have a primary key pt_id and a datetime column order_dts for each id. I want to count the number of keys in each year from 1996-2008 and return eight results - a count for eac

SQL Server 2008 again. I have a primary key pt_id and a datetime column order_dts for each id. I want to count the number of keys in each year from 1996-2008 and return eight results - a count for each year. For a single year

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

works, but how I can I do all of the yea开发者_高级运维rs without having to do something ridiculous like eight different queries?

Thank you!


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)

If you want it all in one row, you can do:

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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消