以天数范围显示数据

时间:2015-03-09 23:16:48

标签: sql sql-server

我有一个SQL查询输出,如下所示

Customer  LastModifiedDate

A          1/12/2013
B          1/1/2015
C          1/28/2015     

现在,我需要显示客户计数,其详细信息在(30-60 days)(61-90 Days)90+等不同日期更新(超过90天) 例如,请参阅下面的输出

DaysRange      CustomersCount

30-60          1
61-90          1
90+            1

请帮助我实现上述输出

2 个答案:

答案 0 :(得分:4)

像这样。

SELECT DaysRange=CASE
                   WHEN Datediff(DAY, LastModifiedDate, Getdate()) BETWEEN 30 AND 60 THEN '30-60'
                   WHEN Datediff(DAY, LastModifiedDate, Getdate()) BETWEEN 61 AND 90 THEN '61-90'
                   WHEN Datediff(DAY, LastModifiedDate, Getdate()) > 90 THEN '90+'
                 END,
       CustomersCount=Count(1)
FROM   yourtable
GROUP  BY CASE
            WHEN Datediff(DAY, LastModifiedDate, Getdate()) BETWEEN 30 AND 60 THEN '30-60'
            WHEN Datediff(DAY, LastModifiedDate, Getdate()) BETWEEN 61 AND 90 THEN '61-90'
            WHEN Datediff(DAY, LastModifiedDate, Getdate()) > 90 THEN '90+'
          END 

答案 1 :(得分:0)

使用此查询:

SELECT COUNT(CASE WHEN DATEDIFF(d, LastModifiedDate, getdate()) BETWEEN 30 AND 60 THEN 1 END) AS [30-60],
       COUNT(CASE WHEN DATEDIFF(d, LastModifiedDate, getdate()) BETWEEN 61 AND 90 THEN 1 end) AS [61-90],
       COUNT(CASE WHEN DATEDIFF(d, LastModifiedDate, getdate()) > 90 THEN 1 END) AS [90+]
   FROM mytable

产生以下输出:

30-60   61-90   90+
1       1       1

使用UNPIVOT,我们可以获得所需的结果集:

SELECT DaysRange, CustomersCount
FROM (
   SELECT COUNT(CASE WHEN DATEDIFF(d, LastModifiedDate, getdate()) BETWEEN 30 AND 60 THEN 1 END) AS [30-60],
          COUNT(CASE WHEN DATEDIFF(d, LastModifiedDate, getdate()) BETWEEN  61 AND 90 THEN 1 END) AS [61-90],
          COUNT(CASE WHEN DATEDIFF(d, LastModifiedDate, getdate()) > 90 THEN 1 END) AS [90+]
   FROM mytable) p
UNPIVOT
   (CustomersCount FOR DaysRange IN ([30-60], [61-90], [90+])
) AS unpvt;

<强>输出:

DaysRange   CustomersCount
30-60       1
61-90       1
90+         1