sql/php-水平和垂直显示记录
所以我有来自基本mySQL select查询的数据,每行输出一个数据 -基本mySQL选择查询sql/php-水平和垂直显示记录,php,mysql,sql,pivot,unpivot,Php,Mysql,Sql,Pivot,Unpivot,所以我有来自基本mySQL select查询的数据,每行输出一个数据 -基本mySQL选择查询 ID---------DATE---------POINT1---POINT2------TOTAL 1----2013-01-03----------10----------16---------26 2----2013-01-03----------11----------22---------33 3----2013-01-03----------15----------7----------2
ID---------DATE---------POINT1---POINT2------TOTAL
1----2013-01-03----------10----------16---------26
2----2013-01-03----------11----------22---------33
3----2013-01-03----------15----------7----------22
1----2013-01-04----------20----------4----------24
2----2013-01-04----------8-----------32---------40
3----2013-01-04----------16----------12---------28
1----2013-01-05----------12----------17---------29
2----2013-01-05----------2-----------29---------31
3----2013-01-05----------8-----------10---------18
我要做的是动态地按列中的日期和行中的id对数据进行排序,比如每月。这是所需的输出
/----------/2013-01-03/---------/2013-01-04/------/2013-01-05/------/
ID--Point 1-Point2-Total-Point 1-Point2-Total-Point 1-Point2-Total
1----10-------16-----26-----20-------4-----24----12-----17------29
2----11-------22-----33------8------32-----40-----2-----29------31
3----15-------7------22-----16------12-----28-----8-----10------18
然后将其输出到csv或excel。我有点不知所措,不知如何才能做到这一点。如果有人能指引我,那就太好了。谢谢您可以取消对列中的数据的pivot,然后执行pivot将所有数据转换回列:
select id,
sum(case when date='2013-01-03' and col='Point1' then value end) Point1_01032013,
sum(case when date='2013-01-03' and col='Point2' then value end) Point2_01032013,
sum(case when date='2013-01-03' and col='Total' then value end) Total_01032013,
sum(case when date='2013-01-04' and col='Point1' then value end) Point1_01042013,
sum(case when date='2013-01-04' and col='Point2' then value end) Point2_01042013,
sum(case when date='2013-01-04' and col='Total' then value end) Total_01042013,
sum(case when date='2013-01-05' and col='Point1' then value end) Point1_01052013,
sum(case when date='2013-01-05' and col='Point2' then value end) Point2_01052013,
sum(case when date='2013-01-05' and col='Total' then value end) Total_01052013
from
(
select id, date_format(date, '%Y-%m-%d') date, 'Point1' col, Point1 as value
from yourtable
union all
select id, date_format(date, '%Y-%m-%d') date, 'Point2' col, Point2
from yourtable
union all
select id, date_format(date, '%Y-%m-%d') date, 'Total' col, Total
from yourtable
) src
group by id;
看
结果是:
| ID | POINT1_01032013 | POINT2_01032013 | TOTAL_01032013 | POINT1_01042013 | POINT2_01042013 | TOTAL_01042013 | POINT1_01052013 | POINT2_01052013 | TOTAL_01052013 |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
| 1 | 10 | 16 | 26 | 20 | 4 | 24 | 12 | 17 | 29 |
| 2 | 11 | 22 | 33 | 8 | 32 | 40 | 2 | 29 | 31 |
| 3 | 15 | 7 | 22 | 16 | 12 | 28 | 8 | 10 | 18 |
哪种关系数据库管理系统?答案因系统而异。嗨,我在使用mysql。谢谢你的回复,非常感谢你的回复^_^