有这两个表
DEPARTMENT
//DEPARTMENT
D# DNAME
-------------------
1 RESEARCH
2 IT
3 SCIENCE
PROJECT
//PROJECT
P# D# BUDGET
-------------------------
1001 1 22500
1002 1 22500
1003 3 50000
当我执行此命令时
SELECT d.D#,DNAME,sum(budget) as "TOTAL BUDGETS"
FROM DEPARTMENT d,PROJECT p
WHERE d.D# = p.D#
GROUP BY d.D#;
我认为结果将是
D# DNAME TOTAL BUDGETS
------------------------------
1 RESEARCH 45000
2 IT 0
3 SCIENCE 50000
但为什么我会收到此错误
//Oracle: NOT A GROUP BY EXPRESSION ERROR
答案 0 :(得分:2)
SELECT列表中的所有列名必须出现在GROUP BY子句中,除非name仅用于聚合函数。
将查询更改为:
SELECT d.D#,DNAME,sum(budget) as "TOTAL BUDGETS"
FROM DEPARTMENT d,PROJECT p
WHERE d.D# = p.D#
GROUP BY d.D#, DNAME;
评论更新:
SELECT d.D#, d.DNAME, NVL(SUM(p.budget), 0) as "TOTAL BUDGETS"
FROM DEPARTMENT d LEFT OUTER JOIN PROJECT p ON d.D#=p.D#
GROUP BY d.D#, d.DNAME;
答案 1 :(得分:0)
SELECT d.D#,max(DNAME),sum(budget) as "TOTAL BUDGETS"
FROM DEPARTMENT d,PROJECT p
WHERE d.D# = p.D#
GROUP BY d.D#;
您应该在GROUP BY
部分中包含该字段,或者使用汇总功能(MAX
或MIN
可以用于此案例)
答案 2 :(得分:0)
您忘记在 GROUP BY 语句中声明d.DNAME
列:
SELECT d.D#,d.DNAME,sum(BUDGET) as "TOTAL BUDGETS"
FROM DEPARTMENT d,PROJECT p
WHERE d.D# = p.D#
GROUP BY d.D#, d.DNAME;
如果要显示所有部门,则需要使用 LEFT JOIN
SELECT d.D#,d.DNAME,sum(BUDGET) as "TOTAL BUDGETS"
FROM DEPARTMENT d
LEFT JOIN PROJECT p
ON d.D# = p.D#
GROUP BY d.D#, d.DNAME;
如果没有项目,则显示0您需要使用 CASE 语句
SELECT d.D#,d.DNAME,
CASE WHEN sum(BUDGET) IS NULL
THEN 0
ELSE sum(BUDGET) END AS "TOTAL BUDGETS"
FROM DEPARTMENT d
LEFT JOIN PROJECT p
ON d.D# = p.D#
GROUP BY d.D#, d.DNAME;
输出:
D# DNAME TOTAL BUDGETS
2 IT 0
1 RESEARCH 45000
3 SEARCH 50000