面试遇到一个表查询问题,我对数据库这方面不太行,求解答
问题描述:
有一个表 year month vaule 1998 1 1.1 1998 2 1.5 1998 3 2.3 2000 1 2.4 2000 2 3 2000 3 6 要求查询出的结果: year m1 m2 m3 1998 1.1 1.5 2.3 2000 2.4 3 6 写出sql
答
SELECT `year`,
sum(case when `month`=1 then `value` end) as m1,
sum(case when `month`=2 then `value` end) as m2,
sum(case when `month`=3 then `value` end) as m3
FROM test GROUP BY `year`
答
就是个数据透视表,使用 case 表达式分组就行。