2011-04-16 79 views
0
Table :tbl_user 
dateofregistration ID  registrationstate 
6-03-11    3   0 
6-03-11    1   0 
6-03-11    2   1 
7-03-11    2   1 
7-03-11    1   1 

我怎麼能顯示導致這樣的SQL Server 2008 Express的如何查詢同一個表的兩個列有兩個條件與GROUPBY

date  TotalID(count)   Total State(0 only) 
6-03-11  3       2 
7-03-11  2       0 

我試圖與這

SELECT CONVERT(varchar(10), dateofregistration, 103) AS Date, 
(select COUNT(ID)) AS Subbase, 
(Select Count(ID)from tbl_User where (registrationstate='0')) AS Totalchurn 
FROM tbl_User 
GROUP BY CONVERT(varchar(10), dateofregistration, 103); 

但錯誤的結果。任何幫助PLZ。

+0

所以**你得到什麼**?!?!?? – 2011-04-16 14:26:07

回答

0

怎麼樣;

select 
    cast(dateofregistration as date), 
    count(distinct id), --or * for all 
    sum(
     case registrationstate when '0' then 1 else 0 end 
    ) 
from tbl_user 
    group by cast(dateofregistration as date) 
    order by 1 


2011-06-03 3 2 
2011-07-03 2 0 
+0

ooh fantastic.Thanks很多。 – Anik 2011-04-18 18:17:34

0
SELECT CONVERT(varchar(10), dateofregistration, 103) AS Date, 
COUNT(1) AS Subbase, 
SUM(CASE WHEN registrationstate='0' THEN 1 ELSE 0 END) AS Totalchurn 
FROM tbl_User 
GROUP BY CONVERT(varchar(10), dateofregistration, 103) 
ORDER BY 1 
+0

您正在爲'CASE' – 2011-04-16 14:32:30

0

你快到了。您不需要爲COUNT(ID)選擇子查詢,因爲這是由GROUP BY處理的。您按日期進行分組,因此計數將是每個日期內的ID數量。我已將計數設置爲不同,以防萬一您可以在一天內註冊多個相同的ID。

您的子查詢幾乎是正確的 - 它需要通過選擇具有相同註冊日期的行與主查詢相關聯。

SELECT CONVERT(varchar(10), dateofregistration, 103) AS Date, 
COUNT(DISTINCT ID) AS TotalID, 
(Select Count(*) from tbl_User t2 where (registrationstate='0') AND t2.registrationdate=t1.registrationdate) AS Totalchurn 
FROM tbl_User t1 
GROUP BY CONVERT(varchar(10), dateofregistration, 103); 
+0

'END'缺少一個結束符號,我一直對'TotalChurn'進行兩次「2」查詢...... – 2011-04-16 14:34:12

相關問題