代码之家  ›  专栏  ›  技术社区  ›  user327301

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

  •  0
  • user327301  · 技术社区  · 15 年前

    SQL Server 2008再次出现。我有一把钥匙 pt_id 和日期时间列 order_dts 对于每个ID,我要计算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')
    

    是的,但是我怎么能这么多年不做像八个不同的问题这样荒谬的事情呢?

    谢谢您!

    2 回复  |  直到 15 年前
        1
  •  5
  •   D'Arcy Rittich    15 年前
    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
    
        2
  •  0
  •   Joe    15 年前
    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)