MySQL查询选择一个不同的列和另一个列中的值的计数,其中列像不同的列? [英] Mysql query to select a distinct column and the count of a value in another column where column like distinct coumn?

查看:52
本文介绍了MySQL查询选择一个不同的列和另一个列中的值的计数,其中列像不同的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据表如下:

ID WEEK   RESULT 
1   13     GOOD
2   13     BAD
3   13     GOOD
4   14     GOOD
5   14     BAD
6   15     BAD

我需要一个sql查询来创建一个数组,如下所示:

I need a sql query to create an array as below:

WWEK   GOOD_COUNT   BAD_COUNT
13            2             1 
14            1             1
15            0             1

任何人都可以帮助我找到合适的mysql查询吗?

Can anyone please help me to find an appropriate mysql query?

推荐答案

您可以使用带有CASE表达式的聚合函数将行转换为列:

You can use an aggregate function with a CASE expression to convert the rows into columns:

select week,
  sum(case when result = 'good' then 1 else 0 end) GoodResult,
  sum(case when result = 'bad' then 1 else 0 end) BadResult
from yt
group by week;

请参见带演示的SQL提琴

这篇关于MySQL查询选择一个不同的列和另一个列中的值的计数,其中列像不同的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆