[英]SQL Server 2008: Count Number of Keys In Multiple Date Ranges Across Multiple Tables
[英]SQL Server 2008: Count Number of Keys In Multiple Date Ranges
再次使用SQL Server 2008。 我有一個主鍵pt_id
和每個ID的datetime列order_dts
。 我想計算1996-2008年每年的密鑰數量,並返回八個結果-每年一次。 一年
SELECT COUNT pm.pt_id AS '1996'
FROM dm.medications pm
WHERE (pm.order_dts BETWEEN '1/1/1996' and '12/31/1996')
可以工作,但是我如何可以多年來不用做像8個不同的查詢這樣荒謬的事情呢?
謝謝!
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
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.