这些查询有什么区别?

时间:2016-08-01 05:46:44

标签: mysql sql database

我试图改进之前编写的查询。这是查询 -

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);

这是我写的查询。但结果似乎有所不同。这里缺少一些东西?

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中的一个真正的菜鸟所以请原谅我,如果它是愚蠢的东西..

2 个答案:

答案 0 :(得分:0)

String

这个SQL与你的不同,请看结果如下:

enter image description here

答案 1 :(得分: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