2013-09-21 77 views
1

這是情景: 有4臺 - CF {ID,姓名} - CLASS {ID,CLASSCODE,CF_ID} - OWNER {ID,AREACODE,CF_ID} - 地區{ID,AREACODE,REGIONCODE}SQL查詢次數歸零具有多個表的JOIN

CF_ID是CF.ID

外鍵指向我想查詢數據庫,以獲得3列: - REGIONCODE - CLASSCODE - FREQUENCY(CF.ID的出現次數),GROUP BY REGIONCODE a nd 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

使用交叉連接,以獲得笛卡爾積,然後左外連接,以確保您不會失去任何。

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