不重复计数查询

时间:2018-11-13 10:14:52

标签: mysql sql

我有一张桌子:

 Item    Status1    Status2
-----------------------------
  A       Good       NULL
  A       Good       NULL
  A       Good       NULL
  A       Bad        Good

  B       Bad        Good
  B       Good       NULL

  C       Good       NULL
  C       Good       NULL      
  C       Good       NULL

  D       Bad        Good

现在,我正在考虑写一个query,它给我以下结果:

 Item     Good     Bad
-----------------------------
  A        4        1
  B        2        1
  C        3        0
  D        1        1

“项目”列中的区别,以及未计算NULL的每个项目的好坏计数。

列名可以是任何东西(我只是在第二张表中将其保留为好和坏)。

关于如何实现我想要的结果的任何建议/想法?

5 个答案:

答案 0 :(得分:4)

使用UNION ALL并进行聚合:

select item, sum(status = 'good'), sum(status = 'bad')
from (select item, status1 as status
      from table t
      union all
      select item, status2
      from table t
     ) t
group by item;

答案 1 :(得分:1)

您可以使用全部并集和条件聚合

select item, count(case when status1='good' then 1 end) as good,
count(case when status1='bad' then 1 end) as bad
from
(
select item , status1 from tablename
union all
select item , status2 from tablename
)A group by item

答案 2 :(得分:1)

在以下情况下使用联合并区分大小写

select Item, sum(case when status = 'good' then 1 else 0 end) as good, 
 sum ( case when status = 'bad' then 1 else 0 end) as bad
from (select Item, Status1 as status
      from table_name
      union all
      select Item, Status2
      from table_name
     ) t
group by Item;

答案 3 :(得分:1)

不需要UNION,只需应用一些逻辑即可。

select Item
  ,sum(case when Status1 = 'Good' then 1 else 0 end +
       case when Status2 = 'Good' then 1 else 0 end) as good
  ,sum(case when Status1 = 'Bad' then 1 else 0 end +
       case when Status2 = 'Bad' then 1 else 0 end) as bad
from tab
group by Item

select Item
  ,count(case when Status1 = 'Good' then 1 end) +
   count(case when Status2 = 'Good' then 1 end) as good
  ,count(case when Status1 = 'Bad' then 1 end) +
   count(case when Status2 = 'Bad' then 1 end) as good
from tab
group by Item

答案 4 :(得分:0)

您可以使用子查询,然后在外部查询中应用求和函数

select distinct(item) as item, sum(S1G+S2G) as Good,sum(S1B+S2B) as Bad from (  select item, CASE WHEN status1 ='Good' THEN 1 ELSE 0 END as S1G, CASE WHEN status2 ='Good' THEN 1 ELSE 0 END as S2G,  CASE WHEN status2 ='Bad' THEN 1 ELSE 0 END as S2B,  CASE WHEN status1 ='Bad' THEN 1 ELSE 0 END as S1B from t1 ) as b group by item

这里是demo