1

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

CF_ID 是指向 CF.ID 的外键

我想查询数据库以获得 3 列: - REGIONCODE - CLASSCODE - 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
4

1 回答 1

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
于 2013-09-21T20:04:13.957 回答