gpt4 book ai didi

sql - SELECT COUNT(*) - 如果没有匹配的行,则返回 0 和分组字段

转载 作者:行者123 更新时间:2023-11-29 11:23:50 24 4
gpt4 key购买 nike

我有以下查询:

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 | sum 
---------+------------+--------
1 | 2 | 0
3 | 4 | 12
5 | 6 | 1234

编辑1

看起来这是不可能的,正如 Matthew PK 解释的那样 in his answer to a similar question .我错误地假设 Postgres 可以以某种方式从 WHERE 子句中提取缺失值。

编辑2

有一些技巧是可以的。 :) 感谢 Erwin Brandstetter!

最佳答案

不可能?已接受的挑战。 :)

WITH x(employee, department) AS (
VALUES
(1::int, 2::int)
,(3, 4)
,(5, 6)
-- ... more combinations
)
SELECT x.employee, x.department, count(i.employee) AS ct
FROM x
LEFT JOIN items i ON i.employee = x.employee
AND i.department = x.department
AND i.available
GROUP BY x.employee, x.department;

这将为您提供完全您所要求的。如果 employeedepartment 不是整数,则转换为匹配类型。

来自@ypercube 的评论:count() 需要在 items 的非空列上,因此对于不存在的标准,我们得到 0,而不是 1

此外,将附加条件拉入 LEFT JOIN 条件(在本例中为 i.available),这样您就不会排除不存在的条件。

性能

解决评论中的其他问题。
这应该表现得很好。对于更长的条件列表,(LEFT) JOIN 可能是最快的方法。

如果您尽快需要它,请务必创建一个 multicolumn index喜欢:

CREATE INDEX items_some_name_idx ON items (employee, department);

如果 (employee, department) 应该是 PRIMARY KEY 或者你应该在两列上有一个 UNIQUE 约束,那会做技巧也是如此。

关于sql - SELECT COUNT(*) - 如果没有匹配的行,则返回 0 和分组字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13803153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com