Sql查询根据加入日期获取客户数量

时间:2013-10-21 05:55:47

标签: sql sql-server

我有一张表“Customers”。

它的列名为“CreatedDate”,表示它是客户的加入日期。

我想计算从当前日期到停止日期的1 - 5年,6 - 10年,11 - 15年间有多少客户,如下所示

Years         No of Customer
0-5           200
6-10          500
11-15         100

详细说明客户创建的日期是“5-5-2010”,而不是当前日期0-5岁的范围。

如果createddate是“5-5-2006”,那么它应该是从当前日期起6到10年的范围内。

3 个答案:

答案 0 :(得分:3)

类似的东西:

with cte as (
  select ((datediff(yy, CreatedDate, getdate()) - 1) / 5) * 5 + 1 as d
  from Customers
)
select
  cast(d as nvarchar(max)) + '-' + cast(d + 4 as nvarchar(max)),
  count(*)
from cte
group by d

<强> sql fiddle demo

答案 1 :(得分:1)

试试这个

SELECT '0-5' as [Years],COUNT(Customer) as [No of Customers] FROM dbo.Customers WHERE DATEDIFF(YY,CreatedDate,GETDATE()) <=5

UNION

SELECT '6-10' as [Years],COUNT(Customer) as [No of Customers] FROM dbo.Customers WHERE DATEDIFF(YY,CreatedDate,GETDATE()) >=5 AND DATEDIFF(YY,CreatedDate,GETDATE()) <=10

UNION

SELECT '11-15' as [Years],COUNT(Customer) as [No of Customers] FROM dbo.Customers WHERE DATEDIFF(YY,CreatedDate,GETDATE()) >=10 AND DATEDIFF(YY,CreatedDate,GETDATE()) <=15

答案 2 :(得分:0)

使用此查询:

With s as(
    SELECT custid,CASE WHEN FLOOR(DATEDIFF(DAY,CREATEDATE,GETDATE())/365)>=1 
                                AND
                                FLOOR(DATEDIFF(DAY,CREATEDATE,GETDATE())/365)<=5 THEN '1-5'
                            WHEN 
                                FLOOR(DATEDIFF(DAY,CREATEDATE,GETDATE())/365)>=6 
                                AND
                                FLOOR(DATEDIFF(DAY,CREATEDATE,GETDATE())/365)<=10 THEN '6-10' END as 'd'
        FROM TABLE)
select count(custid),d
from s 
group by d