嗨,我尝试将这3条语句合并为1条语句,结果集如下(按company_name分组):
- 公司名称
- 雇员(计数)
- 活动(计数)
- 项目(计数)
所有语句都是一个很好的工作。
SELECT c.NAME AS company_name,
COUNT(c2.ID) AS employees
FROM contact c
JOIN relation r ON c.ID = r.FID
JOIN contact c2 ON r.CID = c2.ID
WHERE c.TYPE = 'ORG'
AND c2.TYPE = 'PRS'
GROUP BY c.NAME;
SELECT c.NAME AS company_name,
COUNT(c3.ID) AS activities
FROM contact c
JOIN relation r ON c.ID = r.FID
JOIN activity c3 ON r.CID = c3.ID
WHERE c.TYPE = 'ORG'
GROUP BY c.NAM;
SELECT c.NAME AS company_name,
COUNT(c4.ID) AS projects
FROM contact c
JOIN relation r ON c.ID = r.CID
JOIN project c4 ON r.FID = c4.ID
WHERE c.TYPE = 'ORG'
GROUP BY c.NAM;
字符串
我的结果应该是这样的组合:
以下是迄今为止效果最好的方法,但仍然不正确:
SELECT c.NAME AS company_name,
COUNT(
CASE
WHEN c2.TYPE = 'PRS' THEN c2.ID
END
) AS employees,
COUNT(c3.ID) AS activities,
COUNT(c4.ID) AS projects
FROM contact c
JOIN relation r ON c.ID = r.FID
LEFT JOIN contact c2 ON r.CID = c2.ID
AND c2.TYPE = 'PRS'
LEFT JOIN activity c3 ON r.CID = c3.ID
LEFT JOIN project c4 ON r.FID = c4.ID
WHERE c.TYPE = 'ORG'
GROUP BY c.NAME;
型
2条答案
按热度按时间vwkv1x7d1#
你可以在连接之前进行聚合,这样每个关系最多连接到一个(聚合)行,用于每组员工,活动和项目(这将防止你在使用多个匹配行的结果集的叉积时遇到重复计算的问题),然后在外部查询中,你可以
SUM
预聚合值以获得最终的总和:字符串
GROUP BY
每个公司的唯一标识符,而不是名称,以防止当有两个公司具有相同名称时错误地聚合结果。pgccezyw2#
你可以使用下面的查询,如果它的工作。
字符串