非重复计数查询

g2ieeal7  于 2021-06-18  发布在  Mysql
关注(0)|答案(5)|浏览(202)

我有一张table在下面:

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 不计算在内。
列名可以是任何名称(我只是在第二个表中保留了它的好坏)。
关于如何达到我想要的结果有什么建议/想法吗?

xkftehaa

xkftehaa1#

使用union和case时

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

7nbnzgx92#

可以使用union all和条件聚合

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
tgabmvqs

tgabmvqs3#

不需要联合,只要应用一些逻辑。

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
b1zrtrql

b1zrtrql4#

使用 UNION ALL &do聚合:

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

jrcvhitl5#

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

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

这是演示

相关问题