新手非计算机专业,应日常工作需要作一数据表作财务分析,提问,寻找了无数的网页,求大师帮忙一个sql的问题,最好写个详细代码,情况如下
id 年月 税目 金额
1 2005 营业税 100
2 2006 营业税 200
3 2007 营业税 300
4 2008 营业税 400
5 2009 营业税 500
... .... ... ...
用代码自动转变成
金额 100 200 300 400 500 1500
年月 2005 2006 2007 2008 2009 合计我用php,apache, mysql5.0不知道版本够不?用存储过程?或别的解决方法?请大师们赐教,工作中类似的内容很多,恳请帮忙!!!
看了n多的参考书,n多的网页,大多是mssql的代码
万分感谢
id 年月 税目 金额
1 2005 营业税 100
2 2006 营业税 200
3 2007 营业税 300
4 2008 营业税 400
5 2009 营业税 500
... .... ... ...
用代码自动转变成
金额 100 200 300 400 500 1500
年月 2005 2006 2007 2008 2009 合计我用php,apache, mysql5.0不知道版本够不?用存储过程?或别的解决方法?请大师们赐教,工作中类似的内容很多,恳请帮忙!!!
看了n多的参考书,n多的网页,大多是mssql的代码
万分感谢
[align=center]==== 思想重于技巧 ====
[/align]
.
贴子分数<20:对自已的问题不予重视。
贴子大量未结:对别人的回答不予尊重。
.
#建立测试数据
create table test01(id int, ym int, tax varchar(10), money int)
insert into test01 values (1,2005, 'tax',100),(2,2006, 'tax',200),(3,2007,'tax',300),(4,2008,'tax',400),(5,2009,'tax',500)#建立动态语句
set @s = ' select "ym",',@t = ' ';
select @s := concat( @s, 'sum(case ym when ',ym,' then ', ym ,' else 0 end) as ''',ym,''',') from test01 ;
select @s := concat(@s, '" hj" from test01');
select @t := concat(@t,'sum(case money when ', money,' then ', money,' else 0 end),') from test01;
select @t := concat(' union all select "money",',left(@t,length(@t) - 1), ' ,sum(money) from test01');
select @s := concat(@s,@t);
prepare s1 from @s;
execute s1;
deallocate prepare s1;#运行结果
+-------+------+------+------+------+------+------+
| ym | 2005 | 2006 | 2007 | 2008 | 2009 | hj |
+-------+------+------+------+------+------+------+
| ym | 2005 | 2006 | 2007 | 2008 | 2009 | hj |
| money | 100 | 200 | 300 | 400 | 500 | 1500 |
+-------+------+------+------+------+------+------+