如何在SQL中的相应列中选择不同值的计数?

时间:2015-03-12 15:24:59

标签: mysql sql sqlite

我有一个包含3列的表:第一个是ID(这里不重要),第二个是数字,第三个是答案。第二和第三列数据如下:

number : answer
1      : yes
1      : yes
1      : no
2      : yes
2      : no
3      : yes
3      : no
3      : no

输出应该是

number - total Yes - total No
1      -   2       -  1
2      -   1       -  1
3      -   1       -  2

即。每个数字的总数是和否。有人可以指导我如何编写这个选择查询吗?

2 个答案:

答案 0 :(得分:3)

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

Here is a SQLFiddle

答案 1 :(得分:1)

假设您使用的是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

对于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