oracle SQL用不同的JOIN合并多个语句

mrzz3bfm  于 2023-08-03  发布在  Oracle
关注(0)|答案(2)|浏览(114)

嗨,我尝试将这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;

vwkv1x7d

vwkv1x7d1#

你可以在连接之前进行聚合,这样每个关系最多连接到一个(聚合)行,用于每组员工,活动和项目(这将防止你在使用多个匹配行的结果集的叉积时遇到重复计算的问题),然后在外部查询中,你可以SUM预聚合值以获得最终的总和:

SELECT MAX(c.NAME) AS company_name,
       COALESCE(SUM(e.employees), 0) AS employees,
       COALESCE(SUM(a.activities), 0) AS activities,
       COALESCE(SUM(p.projects), 0) AS projects
FROM   contact c
       INNER JOIN relation r
       ON c.ID = r.FID
       LEFT OUTER JOIN (
           SELECT id,
                  COUNT(id) AS employees
           FROM   contact
           WHERE  TYPE = 'PRS'
           GROUP BY id
       ) e
       ON (r.CID = e.ID)
       LEFT OUTER JOIN (
           SELECT id,
                  COUNT(id) AS activities
           FROM   activity
           GROUP BY id
       ) a
       ON (r.CID = a.ID)
       LEFT OUTER JOIN (
           SELECT id,
                  COUNT(id) AS projects
           FROM   project
           GROUP BY id
       ) p
       ON (r.FID = p.ID)
WHERE  c.TYPE = 'ORG'
GROUP BY c.ID;

字符串

  • 注意:您也可以GROUP BY每个公司的唯一标识符,而不是名称,以防止当有两个公司具有相同名称时错误地聚合结果。
pgccezyw

pgccezyw2#

你可以使用下面的查询,如果它的工作。

SELECT 
    c.NAME AS company_name,
    COUNT(DISTINCT CASE WHEN c2.TYPE = 'PRS' THEN c2.ID END) AS employees,
    COUNT(DISTINCT CASE WHEN c3.ID IS NOT NULL THEN c3.ID END) AS activities,
    COUNT(DISTINCT CASE WHEN c4.ID IS NOT NULL THEN c4.ID END) AS projects
FROM contact c
LEFT 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;

字符串

相关问题