2017-01-27 105 views
-3

我要查詢這三個表,並計算有這三個表1機器ID在一個社區家庭數量:查詢這三個表

machinery [hhmachineryid -  hhid    - machineryid] 
        1   10-10-009-0001    7 
        1   10-07-005-0001    7 
        2   10-02-054-0001    3 

household table [  hhid-   hh_comm_code ] 
        10-01-001-0001  10-01-001 
        10-01-001-0002  10-01-001 

community table [ communitycode -  community] 
        10-01-001    sekondi 
+2

我刪除了不兼容的數據庫標籤,但問題仍然不完整。 –

+0

使用該表格數據,預期的結果是什麼?你能告訴我們你當前的查詢嘗試! – jarlh

+0

社區社區編碼和特定機器的總數 –

回答

0

嘗試這一點 - 但它返回無數據你的輸入:

WITH 
machinery(hhmachineryid,hhid,machineryid) AS (
      SELECT 1,'10-10-009-0001',7 
UNION ALL SELECT 1,'10-07-005-0001',7 
UNION ALL SELECT 2,'10-02-054-0001',3 
) 
, 
household(hhid,hh_comm_code) AS ( 
      SELECT '10-01-001-0001','10-01-001' 
UNION ALL SELECT '10-01-001-0002','10-01-001' 
) 
, 
community(communitycode,community) AS (
SELECT '10-01-001','sekondi' 
) 
SELECT 
    community 
, communitycode 
, COUNT(*) AS household_count 
FROM community c 
JOIN household h 
    ON c.communitycode = h.hh_comm_code 
JOIN machinery m 
    ON h.hhid = m.hhid 
WHERE c.community='sekondi' 
    AND m.machineryid=1 
GROUP BY 
    community 
, communitycode 
; 
+0

MICROSOFT SQL 2014 –