[英]How to select count of different values in the corresponding column in SQL?
I have a table with 3 columns: first one is ID(not important here), second is number, and third is answer. 我有一个包含3列的表格:第一个是ID(此处不重要),第二个是数字,第三个是答案。 The second and third column data is as follows: 第二和第三列数据如下:
number : answer
1 : yes
1 : yes
1 : no
2 : yes
2 : no
3 : yes
3 : no
3 : no
The output is supposed to be 输出应该是
number - total Yes - total No
1 - 2 - 1
2 - 1 - 1
3 - 1 - 2
ie the total number of yes and no for each number. 即每个数字为是和否的总数。 Can someone guide me as to how to write this select query? 有人可以指导我如何编写此选择查询吗?
SELECT
number,
COUNT(CASE WHEN answer = 'yes' THEN 1 END) AS total_yes,
COUNT(CASE WHEN answer = 'no' THEN 1 END) AS total_no
FROM test_table
GROUP BY number
Assuming you are using sqlite then it will be as follows: 假设您正在使用sqlite,则它将如下所示:
Select Cast(number as varchar) || ' - ' ||
Cast(Sum(case when answer = 'Yes' then 1 else 0 end) as varchar) || ' - ' ||
Cast(SUM(case when answer = 'No' then 1 else 0 end) as varchar)
from table
Group by number
For MySQL it will be: 对于MySQL,它将是:
Select CONCAT_WS(' - ', Cast(number as char),
Cast(Sum(case when answer = 'Yes' then 1 else 0 end) as char),
Cast(SUM(case when answer = 'No' then 1 else 0 end) as char))
from table
Group by number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.