求一SQL查询语句(最好是mysql)
怎么把这样一个表儿
year month amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
查成这样一个结果
year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4
[解决办法]
这不是行列转换吗,a表示表名
SELECT
YEAR,
SUM(IF(MONTH=1,amount,0)) AS m1,
SUM(IF(MONTH=2,amount,0)) AS m2,
SUM(IF(MONTH=3,amount,0)) AS m3,
SUM(IF(MONTH=4,amount,0)) AS m4
FROM a
GROUP BY YEAR
[解决办法]
SELECT
YEAR,
SUM(CASE MONTH WHEN 1 THEN amount ELSE 0 END) AS m1,
SUM(CASE MONTH WHEN 2 THEN amount ELSE 0 END) AS m2,
SUM(CASE MONTH WHEN 3 THEN amount ELSE 0 END) AS m3,
SUM(CASE MONTH WHEN 4 THEN amount ELSE 0 END) AS m4
FROM a
GROUP BY YEAR
用 case when zhen 的语法也可以,结果一样,这个数据是死的 ,如果数据是动态的就不行了。。
就必须用变量了
[解决办法]
select a.year,sum(if(a.month='1',amount,'0')) as 'm1',
sum(if(a.month='2',amount,0)) as 'm2',
sum(if(a.month='3',amount,0)) as 'm3',
sum(if(a.month='4',amount,0)) as 'm4'
from row_column_test a
group by a.year;
[解决办法]
CREATE TABLE t1( nian INT, yue INT, amount DECIMAL(18,1))INSERT INTO t1SELECT 1991, 1, 1.1 UNION ALLSELECT 1991, 2, 1.2 UNION ALLSELECT 1991, 3, 1.3 UNION ALLSELECT 1991, 4, 1.4 UNION ALLSELECT 1992, 1, 2.1 UNION ALLSELECT 1992, 2, 2.2 UNION ALLSELECT 1992, 3, 2.3 UNION ALLSELECT 1992, 4, 2.4SELECT * FROM t1DECLARE @str VARCHAR(8000)SET @str='select nian'SELECT @str=@str+',max(case when yue='+LTRIM(yue)+' then amount else 0 end) as ['+LTRIM(yue)+']'FROM (SELECT DISTINCT yue FROM t1) AS a1SET @str=@str+' from t1 group by nian'PRINT @strEXEC (@str)-----------------nian 1 2 3 41991 1.1 1.2 1.3 1.41992 2.1 2.2 2.3 2.4
[解决办法]
字段名调整了下
DECLARE @str VARCHAR(8000)SET @str='select nian'SELECT @str=@str+',max(case when yue='+LTRIM(yue)+' then amount else 0 end) as [m'+LTRIM(yue)+']'FROM (SELECT DISTINCT yue FROM t1) AS a1SET @str=@str+' from t1 group by nian'PRINT @strEXEC (@str)---------------------nian m1 m2 m3 m41991 1.1 1.2 1.3 1.41992 2.1 2.2 2.3 2.4