【发布时间】:2012-11-27 23:54:48
【问题描述】:
我有以下疑问:
SELECT employee,department,count(*) AS sum FROM items
WHERE ((employee = 1 AND department = 2) OR
(employee = 3 AND department = 4) OR
(employee = 5 AND department = 6) OR
([more conditions with the same structure]))
AND available = true
GROUP BY employee, department;
如果一对“employee-department”没有项目,则查询不返回任何内容。我希望它返回零:
employee | department | sum
---------+------------+--------
1 | 2 | 0
3 | 4 | 12
5 | 6 | 1234
编辑1
看起来这是不可能的,正如 Matthew PK 解释的 in his answer to a similar question。我错误地假设 Postgres 可以以某种方式从 WHERE 子句中提取缺失值。
EDIT2
有一些技巧是可能的。 :) 感谢 Erwin Brandstetter!
【问题讨论】:
-
您只想要 WHERE 子句中的员工和部门组吗?
-
@FarukSahin,实际上没有,可能还有其他条款,但我只想按“员工”和“部门”分组。相应地更新了问题
-
@FarukSahin,误读了您的评论。在输出中,我只想要分组字段和总和。
-
所以,您想限制某些(员工、部门)组的输出,而不希望所有(员工、部门)组?
-
我没有看到标签是postgresql。检查此链接,其中完全相同的问题得到解答:stackoverflow.com/questions/4866162/…
标签: sql postgresql count left-join aggregate-functions