2014-04-29 88 views
1

我試圖獲得5列,第一列是評估單元(EU),但在接下來的4列中,我要計算有多少家庭(不同的INSTANCE_ID_HOUSE)符合特定標準,但數據由居民儲存。這裏有4個查詢我使用的(我基本上只是想將它們組合成一個查詢):在GROUP BY級別使用「CASE」命令

SELECT EU, COUNT(DISTINCT INSTANCE_ID_HOUSE) FROM SENEGAL_CLEAN 
WHERE CLUSTER_COMPLETE>0 
GROUP BY EU 
ORDER BY EU ASC 

SELECT COUNT(DISTINCT INSTANCE_ID_HOUSE) FROM SENEGAL_CLEAN 
WHERE CLUSTER_COMPLETE>0 AND (W1_DRINK_SOURCE=1 OR W1_DRINK_SOURCE=4) 
GROUP BY EU 
ORDER BY EU ASC 

SELECT COUNT(DISTINCT INSTANCE_ID_HOUSE) FROM SENEGAL_CLEAN 
WHERE CLUSTER_COMPLETE>0 AND (W2_GET_DRINK_WATER=1 OR W2_GET_DRINK_WATER=2) 
GROUP BY EU 
ORDER BY EU ASC 

SELECT COUNT(DISTINCT INSTANCE_ID_HOUSE) FROM SENEGAL_CLEAN 
WHERE CLUSTER_COMPLETE>0 AND (S2_SEE_LATRINE=1 OR S2_SEE_LATRINE=2) 
GROUP BY EU 
ORDER BY EU ASC 

回答

2

可以使用case語句爲您計數:

select 
    eu, 
    count (distinct case when cluster_complete > 0 then instance_id_house else null end) as YourAliasHere, 
    count (distinct when cluster_complete > 0 and (W1_DRINK_SOURCE=1 OR W1_DRINK_SOURCE=4) then instance_id_house else null end) as YourNextAlias\ 
    ... 
FROM SENEGAL_CLEAN 
group by EU 

所以你指望每個instance_id_house它符合每個案例陳述中的標準。我認爲你可以留下你的where子句(根據你現在展示的內容)。

0

嘗試是這樣的:

Select S.EU,t1.c1 , t2.c2, t3.c3, t4.c4 
From SENEGAL_CLEAN S 
inner join(

SELECT EU, COUNT(DISTINCT INSTANCE_ID_HOUSE) c1 FROM SENEGAL_CLEAN 
WHERE CLUSTER_COMPLETE>0 
GROUP BY EU 
)t1 on t1.Eu= s.Eu 

inner join(
SELECT EU,COUNT(DISTINCT INSTANCE_ID_HOUSE) c2 FROM SENEGAL_CLEAN 
WHERE CLUSTER_COMPLETE>0 AND (W1_DRINK_SOURCE=1 OR W1_DRINK_SOURCE=4) 
GROUP BY EU 
)t2 on t2.Eu= s.Eu 

inner join(
SELECT Eu,COUNT(DISTINCT INSTANCE_ID_HOUSE) c3 FROM SENEGAL_CLEAN 
WHERE CLUSTER_COMPLETE>0 AND (W2_GET_DRINK_WATER=1 OR W2_GET_DRINK_WATER=2) 
GROUP BY EU 
)t3 on t3.Eu= s.Eu 

inner join(
SELECT Eu,COUNT(DISTINCT INSTANCE_ID_HOUSE) c4 FROM SENEGAL_CLEAN 
WHERE CLUSTER_COMPLETE>0 AND (S2_SEE_LATRINE=1 OR S2_SEE_LATRINE=2) 
GROUP BY EU 
)t4 on t4.Eu = s.Eu 

SqlFiddle:http://sqlfiddle.com/#!9/90b33/1

+0

我得到了以下錯誤信息:#1052 - 在字段列表列「EU」是不明確的(我想弄明白,但你可能會更快) – beck777

+0

我編輯了我的答案,注意查詢的第一行 – RezaRahmati

+0

#1054 - 在'子句' – beck777