mysql 按时间 垂直_mysql数据透视表日期(垂直于水平数据)

为了获得此结果,您需要透视数据. MySQL没有pivot函数,但你可以使用带有CASE表达式的聚合函数.

如果已知日期数,则可以对查询进行硬编码:

select client_id,

max(case when rownum = 1 then date end) Date1,

max(case when rownum = 2 then date end) Date2,

max(case when rownum = 3 then date end) Date3

from

(

select client_id,

date,

@row:=if(@prev=client_id, @row,0) + 1 as rownum,

@prev:=client_id

from yourtable, (SELECT @row:=0, @prev:=null) r

order by client_id, date

) s

group by client_id

order by client_id, date

我实现了用户变量来为client_id组中的每条记录分配一个行号.

如果您的日期数量未知,则需要使用预准备语句动态创建sql:

SET @sql = NULL;

SELECT

GROUP_CONCAT(DISTINCT

CONCAT(

'MAX(CASE WHEN rownum = ',

rownum,

' THEN date END) AS Date_',

rownum

)

) INTO @sql

from

(

select client_id,

date,

@row:=if(@prev=client_id, @row,0) + 1 as rownum,

@prev:=client_id

from yourtable, (SELECT @row:=0) r

order by client_id, date

) s

order by client_id, date;

SET @sql

= CONCAT('SELECT client_id, ', @sql, '

from

(

select client_id,

date,

@row:=if(@prev=client_id, @row,0) + 1 as rownum,

@prev:=client_id

from yourtable, (SELECT @row:=0) r

order by client_id, date

) s

group by client_id

order by client_id, date');

PREPARE stmt FROM @sql;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;

他们都给出了结果:

| CLIENT_ID | DATE_1 | DATE_2 | DATE_3 |

--------------------------------------------------------------------------------------------------------------

| 1 | February, 03 2013 00:00:00+0000 | February, 10 2013 00:00:00+0000 | May, 12 2013 00:00:00+0000 |

| 2 | February, 03 2013 00:00:00+0000 | July, 15 2013 00:00:00+0000 | (null) |

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值