2013-10-21 61 views
2

我有一個表「Customers」。sql查詢根據加入日期獲取客戶數

它有一個列名「CreatedDate」,表示它是客戶的加入日期。

我要計算有多少客戶是1-5歲之間,6 - 10年,從當前日期11-15年ceateddate,像下面

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

詳細,如果客​​戶createddate是「 5-5-2010「,應該在距離當前日期0-5年的範圍內。

如果createddate是「5-5-2006」,則應該在距離當前日期6-10年的範圍內。

+0

感謝您的快速響應,我只將客戶的NoOfCustomer的select count(CustomerID)我是數據庫newbei,所以不知道如何把日期條件。 – AnandMeena

+0

看起來我被毆打了,哈哈。 – codemonkeh

+0

對不起@codemonkeh,你的意思是? – AnandMeena

回答

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

+0

謝謝@羅曼,但它沒有給出正確的結果。表格中最早創建的日期是「2008-01-18」,它也給出了11-15的結果。所以我覺得這裏有些不對。 – AnandMeena

+0

對不起@羅曼,我的錯誤,它有一些比10年前更久的日期。它工作正常,再次感謝:-)。 – AnandMeena

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 
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 
+0

謝謝@Rahul,但是如果有更多年如16-20,21-25等等呢? – AnandMeena