SQL查询COUNT与多个表JOIN一起返回零

时间:2013-09-21 19:56:43

标签: sql select join count

这是场景: 有4个表 - CF {ID,NAME} - CLASS {ID,CLASSCODE,CF_ID} - 所有者{ID,AREACODE,CF_ID} - REGION {ID,AREACODE,REGIONCODE}

CF_ID是指向CF.ID

的外键

我想查询数据库以获得3列: - REGIONCODE - 班级代码 - FREQUENCY(CF.ID的出现次数),GROUP BY REGIONCODE和CLASSCODE

棘手的部分是查询返回的数据集应包含频率为0的行,以防在特定的REGIONCODE中找不到特定的CLASSCODE。 基本上我希望每个CLASSCODE(DISTINCT)都有REGIONCODE(DISTINCT)的carthesian乘积,即使FREQUENCY为零,也要列举所有出现的事件。

这是我写的查询:

SELECT 
REGION.REGIONCODE, CLASS.CLASSCODE, COUNT(CF.ID) AS Frequency 
FROM REGION 
JOIN OWNER ON REGION.AREACODE = OWNER.AREACODE
JOIN CF ON OWNER.CF_ID = CF.ID 
JOIN CLASS ON CLASS.CF_ID = CF.ID
GROUP BY CLASS.CLASSCODE, REGION.REGIONCODE
ORDER BY REGION.REGIONCODE, CLASS.CLASSCODE

1 个答案:

答案 0 :(得分:1)

使用交叉连接获取笛卡尔积,然后离开外连接以确保不会丢失。

Select
    r.RegionCode,
    c.ClassCode,
    Count(cf.Id) AS Frequency 
From
    Region r
        Cross Join
    Class c
        Left Outer Join
    Owner o
        On r.AreaCode = o.AreaCode
        Left Outer Join
    CF
        On o.Cf_Id = cf.Id And
           c.Cf_Id = cf.Id
Group By
    c.ClassCode,
    r.RegionCode
Order By
    r.RegionCode,
    c.ClassCode