2016-08-01 60 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