我有以下查询:
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;
Run Code Online (Sandbox Code Playgroud)
如果"employee-department"对没有项目,则查询不返回任何内容.我希望它返回零代替:
employee | department | sum
---------+------------+--------
1 | 2 | 0
3 | 4 | 12
5 | 6 | 1234
Run Code Online (Sandbox Code Playgroud)
看起来这是不可能的,正如Matthew PK 在他对类似问题的回答中所解释的那样.我错误地假设Postgres可以以某种方式从WHERE子句中提取缺失值.
有一些技能是可能的.:)感谢Erwin Brandstetter!
我有一个简单的查询:
Select qty from X where id=....;
Run Code Online (Sandbox Code Playgroud)
此查询始终返回0或1行.当它返回1行时一切正常.但如果它返回0行,我的查询将失败,因为qty在计算中使用.(这是Select statment中的Sub查询).
我需要以某种方式确保查询始终返回1行.
我试过了:
Select coalesce(qty,0) from X where id=....;
Run Code Online (Sandbox Code Playgroud)
但它没有帮助,好像没有行,合并是没用的.如果没有发现它应该给出的行0
我该如何解决?