2

我有一张桌子“ 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 年的范围内。

4

3 回答 3

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

于 2013-10-21T06:17:15.600 回答
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
于 2013-10-21T06:33:10.330 回答
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
于 2013-10-21T06:18:29.060 回答