使用GROUP BY进行SELECT,并显示包含两个表的总计

时间:2014-04-25 10:18:50

标签: mysql sql oracle

有两张桌子

部门表

//Department
D#          DNAME
-------------------
1           SALES
2        ACCOUNTING
3          GAMES
5          SPORTS

项目表

//Project
P#      D#
-----------
1001     1
1002     3
1003     5
1004     5

输出显示时应该是:

Department    Total Project
---------------------------
  1               1
  2               0
  3               1
  5               2

目前我的陈述

SELECT D# FROM DEPARTMENT 
   WHERE (SELECT COUNT(*) FROM PROJECT WHERE DEPARTMENT.D# = PROJECT.D#);

但如果D#中没有任何项目,我应该显示0?

4 个答案:

答案 0 :(得分:1)

SELECT D.D#,
   COUNT(p.P#)
FROM Department d
LEFT JOIN Project p
ON Project.D#=Department.D
GROUP BY d.D#; 

答案 1 :(得分:0)

试试这个:

    SELECT D# , CASE WHEN A.COUNT > 0  THEN D# ELSE 0 END AS TOTAL_PROJECT 
    FROM DEPARTMENT JOIN (SELECT D# , COUNT(*) FROM PROJECT GROUP BY PROJECT.D#) A ON
 DEPARTMENT.D# = A.D#;

答案 2 :(得分:0)

与group by的简单左连接可以达到这样的要求。

SELECT 
  DEPARTMENT.D#,
  COUNT(PROJECT.P#) AS TotalProject
FROM DEPARTMENT
LEFT JOIN PROJECT ON DEPARTMENT.D# = PROJECT.D#
GROUP BY DEPARTMENT.D# 

答案 3 :(得分:0)

检查以下查询:

SELECT 
D# as 'Dept_ID',count(P#) as 'Count'
from 
department d 
left join project p 
on d.D#=p.D# 
group by d.D#;