2013-12-19 34 views
1
CREATE TABLE interview (uniqueID int identity(1,1), 
         date datetime, 
         recordtype int, 
         amount numeric(18, 4)) 

INSERT INTO interview values('6/30/13', 1, 27.95) 
INSERT INTO interview values('5/20/13', 1, 21.85) 
INSERT INTO interview values('5/22/13', 2, 27.90) 
INSERT INTO interview values('12/11/12', 2, 23.95) 
INSERT INTO interview values('6/13/13', 3, 24.90) 
INSERT INTO interview values('6/30/13', 2, 27.95) 
INSERT INTO interview values('5/20/13', 2, 21.85) 
INSERT INTO interview values('5/22/13', 1, 27.90) 
INSERT INTO interview values('12/11/12',1, 23.95) 
INSERT INTO interview values('6/13/13', 3, 24.90) 
INSERT INTO interview values('6/30/13', 3, 27.95) 
INSERT INTO interview values('5/20/13', 3, 21.85) 
INSERT INTO interview values('5/22/13', 2, 27.90) 
INSERT INTO interview values('12/11/12', 1, 23.95) 
INSERT INTO interview values('6/13/13', 1, 24.90) 

如何獲得以下結果?查詢會是什麼樣子?SQL加入查詢如何到

Query Result

我只能得到部分的工作,但我的答案是不正確的。我需要 以某種方式加入查詢。

select distinct date, count(RecordType)as Count_unique1 
from interview 
where RecordType = '1' 
group by date 

select distinct date, count(RecordType)as Count_unique2 
from interview 
where RecordType = '2' 
group by date 

select distinct date, count(RecordType)as Count_unique3 
from interview 
where RecordType = '3' 
group by date 
+0

嘗試此鏈接:http://technet.microsoft.com/en-us/library/aa172756%28v = sql.80%29.aspx – SK2185

+0

RecordType在所有情況下都是1,2,3,或者可能會有所不同? –

回答

3
select 
date, 
sum(case when RecordType = '1' then 1 else 0 end) as Count_unique1, 
sum(case when RecordType = '2' then 1 else 0 end) as Count_unique2, 
sum(case when RecordType = '3' then 1 else 0 end) as Count_unique3 
from interview 
group by date 
0

如果記錄類型是在所有的情況下,這將是足夠的1,2和3。

select date, 
sum(RecordType = '1') as Count_unique1, 
sum(RecordType = '2') as Count_unique2, 
sum(RecordType = '3') as Count_unique3 
from interview 
group by date 
+0

Msg 102,Level 15,State 1,Line 3 '='附近的語法不正確。 – user1929393

1

另外在MSSQL你可以使用PIVOT

SELECT date, [1] AS Count_unique1, 
      [2] AS Count_unique2, 
      [3] AS Count_unique3 
FROM (SELECT date,recordtype,amount FROM interview) p 
PIVOT 
(
    COUNT (amount) 
    FOR recordtype IN ([1], [2], [3]) 
) AS pvt 
ORDER BY pvt.date; 

SQLFiddle demo

+0

Msg 325,Level 15,State 1,Line 5 「PIVOT」附近的語法不正確。您可能需要將當前數據庫的兼容級別設置爲更高的值才能啓用此功能。請參閱ALTER DATABASE的SET COMPATIBILITY_LEVEL選項的幫助。 – user1929393