创建复杂的SQL查询

时间:2013-08-29 07:30:38

标签: sql select

我有3张桌子:

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中的行数重复
  4. 输出:

    ID    Name    Count
    1     R       2
    3     B       0
    

    感谢

2 个答案:

答案 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

答案 1 :(得分: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,