根据日期列上的间隔(天)组计算记录

时间:2012-10-17 06:18:31

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

计算间隔之间的数据,间隔取决于记录的年龄

我有一个名为complaint的表格,其中我有许多列ComplaintDate,我想显示记录数取决于间隔

以下间隔将用于分类记录:

  1. 10天以上的投标数量。
  2. 比10-20天更长的投标数量。
  3. 比较年长20-30天的投诉数量。
  4. 超过30天的评估数量。
  5. 我尝试过这样的事情

    select SUM(CASE WHEN ComplaintDate BETWEEN DATEADD (dd,-10,getdate())AND   GETDATE()  THEN 1 ELSE 0 END) As '0-10',
           SUM(CASE WHEN ComplaintDate BETWEEN  DATEADD (dd,-20,getdate()) AND DATEADD (dd,-10,getdate()) THEN 1 ELSE 0 END) AS '10-20',
           SUM(CASE WHEN ComplaintDate BETWEEN DATEADD (dd,-30,getdate()) AND DATEADD (dd,-20,getdate()) THEN 1 ELSE 0 END) AS '20-30'       
     FROM Complaint 
    

    我也希望0-10天间隔内包含的那一天不应计入10-20或20-30天间隔,同样也应该适用于其他其他间隔。

1 个答案:

答案 0 :(得分:0)

select 
SUM(CASE WHEN ComplaintDate > DATEADD (dd,-10,getdate()) AND   ComplaintDate <= GETDATE()  THEN 1 ELSE 0 END) As '0-10',

SUM(CASE WHEN ComplaintDate > DATEADD (dd,-20,getdate()) AND ComplaintDate<=DATEADD (dd,-10,getdate()) THEN 1 ELSE 0 END) AS '10-20',

SUM(CASE WHEN ComplaintDate > DATEADD (dd,-30,getdate()) AND ComplaintDate <=DATEADD (dd,-20,getdate()) THEN 1 ELSE 0 END) AS '20-30'    

FROM Complaint