2013-08-29 103 views
-4

我有3個表:創建複雜的SQL查詢

TB1:

ID   Name  
1    R 
2    F 
3    B 

TB2:

ID1  
1 
2  
1  
2  
2  

TB3:

ID1   Stat 
1     20 
2     10 
3     20 

我需要一個SQL查詢返回低於規格:

  1. ID,名稱從TB1和行的計數從TB2
  2. 在TB3 STAT = 20行的行
  3. 計數在TB2

OUTPUT重複:

ID    Name    Count 
1     R       2 
3     B       0 

謝謝

+0

哪個數據庫? –

回答

0
select a.id, a.name, count(b.id1) 
from table1 a join table3 c 
on a.id = c.id1 and c.stat = 20 
left join table2 b on a.id = b.id1 
group by a.id, a.name 
0
SELECT TB1.ID, 
     TB1.Name, 
     SUM(CASE WHEN TB2.ID1 IS NULL THEN 0 ELSE 1 END) AS Repeat 
FROM TB1 
     JOIN TB3 
      ON TB1.ID = TB3.ID1 
      AND TB3.STAT = 20 
     LEFT JOIN TB2 
      ON TB1.ID = TB2.ID1 
GROUP BY TB1.ID, 
     TB1.Name,