2016-08-01 103 views
0

我試圖改進以前寫的查詢。這是查詢 -這些查詢有什麼不同?

select tq.feature as Feature, tq.Total, pq.Passed 
from (
    select feature, count(distinct id) as Total 
    from X.results 
    where ver = '4.2' 
    group by feature 
) as tq 
LEFT JOIN (
    select feature, count(distinct id) as Passed 
    from X.results 
    where ver = '4.2' and result = 'pass' 
    group by feature 
) as pq USING (feature); 

這是我寫的查詢。但結果似乎是不同的.Am在這裏丟失的東西?

select feature,count(distinct id) as totalcases, 
    sum(case when result = 'PASS' then 1 else 0 end) as passed 
from X.results 
where ver='4.2' 
group by feature 
order by feature; 

我在SQL一個真實的小白所以請原諒我,如果這件事情傻..

+0

發佈您的查詢結果和您的預期結果。 –

+1

您的第一個查詢會爲通過計數不同的ID。你的第二個查詢不是。它只是獲得每個功能的PASS記錄計數 – ughai

+0

計數之後的總和(獨特的id),是不是隻考慮了不同的ID? – RAHUL

回答

0

一種方法是根據結果和功能進行分組,然後再對另一個功能進行聚合。像這樣的東西。

SELECT 
    feature, 
    SUM(id_count) totalcases, 
    SUM(CASE WHEN result = 'PASS' THEN id_count ELSE 0 END) passed 
FROM 
(
    SELECT 
    feature, 
    CASE WHEN result = 'PASS' THEN 'PASS' ELSE 'OTHER' END result, 
    COUNT(distinct id) id_count 
    FROM x.results 
    WHERE ver='4.2' 
    GROUP BY feature,CASE WHEN result = 'PASS' THEN 'PASS' ELSE 'OTHER' END 
) x 
GROUP BY feature 
ORDER BY feature 
+0

這似乎是工作。謝謝。我會看看我做了什麼錯誤。 – RAHUL

0
SELECT feature, count(distinct id) AS Total, 
    count(distinct if (result='pass', id, null)) AS passed 
FROM X.results 
WHERE ver = '4.2' 
GROUP BY 1 ORDER BY 1; 

這SQL和你不一樣,請參考如下結果:

enter image description here

+0

好吧,這給出了與我的查詢相同的結果。 :| – RAHUL

+0

我的SQL與你的不同。如果結果發生相同,您能否給我們一份樣品數據清單? – SIDU