我有问题要解决。
我有两个表,institutions 和 documents,它们通过文档 owner_id 和 institution id 连接:
机构
id | name
----+-----
1 | a
2 | b
3 | c
4 | d
和
文件
id | owner | value
----+-------+------
1 | 1 | xxx
2 | 1 | yyy
3 | 1 | yyy
4 | 3 | xxx
5 | 3 | xxx
6 | 4 | yyy
然后我需要统计,每个名字有多少个值,这样的结果:
name | count(total) | count(xxx) | count(yyy)
------+--------------+------------+------------
a | 3 | 1 | 2
b | 0 | 0 | 0
c | 2 | 2 | 0
d | 1 | 0 | 1
我试过这个查询:
SELECT
a.name,
(a.xxx + b.yyy) as total,
a.xxx,
b.yyy
FROM
(SELECT count(documents.id) as xxx,
institution.name
FROM
documents, institution
WHERE
documents.owner_id = institution.id and
documents.value = 'xxx'
GROUP BY
institution.name) as a,
(SELECT count(documents.id) as yyy,
institution.name
FROM
documents,
institution
WHERE
documents.owner_id = institution.id and
documents.value = 'yyy'
GROUP BY
institution.name) as b
WHERE
a.name = b.name
ORDER BY
a.name
但它只返回那些行,其中 xxx 和 yyy 不是 epmty,这种:
name | count(total) | count(xxx) | count(yyy)
------+--------------+------------+------------
a | 3 | 1 | 2
我缺少这些行:
name | count(total) | count(xxx) | count(yyy)
------+--------------+------------+------------
b | 0 | 0 | 0
c | 2 | 2 | 0
d | 1 | 0 | 1
因为它包含空数据。 提前致谢。
朱利叶斯
最佳答案
它可以更容易,试试这个解决方案
SELECT i.name,
COUNT(*) total,
COUNT(CASE d.value WHEN 'xxx' THEN 1 ELSE NULL END) x_cnt,
COUNT(CASE d.value WHEN 'yyy' THEN 1 ELSE NULL END) y_cnt
FROM institution i
LEFT JOIN documents d ON d.owner = i.id
GROUP BY i.name
关于sql - PostgreSQL 从两个表中选择空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29669387/