2013-07-17 46 views
0

沒有數據我有兩個表TAB1和TAB2計數加零到曾經有現場

TAB1:

 
ID NAME 
1 Supreeth 
2 Aishu 
3 Arvi 
4 Gani 

TAB2:

 
ID DESIGN 
1 A 
1 B 
4 B 
4 C 
2 A 
3 B 
3 B 

我試圖讓設計計數,我得到以下輸出

 
NAME  DESIGN Count(DESIGN) 
Supreeth  A  1 
Supreeth  B  1 
Aishu   A  1 
Arvi   B  2 
Gani   B  1 
Gani   C  1 

我想查詢是

SELECT TAB1.NAME,TAB2.DESIGN, COUNT(DESIGN) 
FROM TAB1 , TAB2 
WHERE TAB1.ID=TAB2.ID 
GROUP BY TAB1.NAME,TAB2.DESIGN,TAB1.ID 
ORDER BY TAB1.ID 

但是我正在尋找的輸出像

 

NAME  DESIGN Count(DESIGN) 
Supreeth  A  1 
Supreeth  B  1 
Supreeth  C  0 
Aishu   A  1 
Aishu   B  0 
Aishu   C  0 
Arvi   A  0 
Arvi   B  2 
Arvi   C  0 
Gani   A  0 
Gani   B  1 
Gani   C  1 



請告訴我如何做到這一點使用SQL查詢。在此先感謝

+0

什麼類型的數據庫是這樣嗎? –

+0

你正在使用哪種數據庫? – Rohan

+0

@ R.S:ORACLE數據庫 – user2590547

回答

3

試試這個:

SELECT 
    TAB1.ID, 
    TAB1.NAME,TAB2.DESIGN, 
    SUM(CASE WHEN TAB1.ID=TAB2.ID THEN 1 ELSE 0 END) as count 
FROM 
    TAB1 CROSS JOIN TAB2 
GROUP BY 
    TAB1.ID,TAB1.NAME,TAB2.DESIGN 
ORDER BY 
    TAB1.ID 

SQLFiddle

+0

與OP Query相同。 – Luv

+2

非常不同。總數不算。嘗試一下。它給出了OP想要的結果:) –

0

試試這個

SELECT T1.[ID], T1.[NAME],T2.[DESIGN], 
(
    SELECT COUNT([DESIGN]) FROM TAB2 TT2 WHERE TT2.ID=T1.ID AND TT2.[DESIGN] = T2.[DESIGN] 
) AS CNT 
FROM TAB1 T1 
CROSS JOIN 
(
    SELECT [DESIGN] FROM TAB2 GROUP BY [DESIGN] 
) T2 
ORDER BY T1.[NAME],T2.[DESIGN] 

SQL FIDDLE DEMO