0

假设我有这张桌子:

NAME    YEAR    SCORE
_____________________
User1   2010    1
User2   2011    3
User3   2012    2
User4   2013    1
User5   2012    1
User6   2011    3
User7   2010    4
User8   2011    1

我想创建一个查询,其输出如下所示:

YEAR    1    2    3    4
________________________
2010    1    0    0    1
2011    1    0    2    0
2012    1    1    0    0
2013    1    0    0    0

其中编号列中的值是该分数在给定年份出现的次数的计数。这似乎应该很容易,但我无法弄清楚如何以静态的方式编写此查询。想法?

4

2 回答 2

0
select  YEAR,
    count(CASE WHEN SCORE = 1 THEN 1 END) AS `1`,
    count(CASE WHEN SCORE = 2 THEN 1 END) AS `2`,
    count(CASE WHEN SCORE = 3 THEN 1 END) AS `3`,
    count(CASE WHEN SCORE = 4 THEN 1 END) AS `4`
from TABLE
group by year
于 2013-11-12T19:40:17.160 回答
0

对于一组四个值

SELECT YEAR, SUM(CASE WHEN SCORE = 1 THEN 1 ELSE 0 END) AS `1`, 
SUM(CASE WHEN SCORE = 2 THEN 1 ELSE 0 END) AS `2`,
SUM(CASE WHEN SCORE = 3 THEN 1 ELSE 0 END) AS `3`,
SUM(CASE WHEN SCORE = 4 THEN 1 ELSE 0 END) AS `4`
FROM TABLE
GROUP BY YEAR
于 2013-11-12T19:41:02.460 回答