MySql-Pivot表

时间:2017-09-26 16:21:58

标签: mysql sql pivot-table

我有一个包含记录的数据库表(return_period)

id  ReturnPeriod    Value   Date
1   10              10X     11/1/2012
2   20              20x     11/1/2012
3   30              30x     11/1/2012
4   10              10xx    12/1/2013
5   20              20xx    12/1/2013
6   30              30y     1/1/2015
7   30              303     1/1/2015

并期望输出表如下:

Date      Rp10_Value    Rp20_Value  Rp30_Value
11/1/2012    10x          20x         30x
12/1/2013    10XX         20XX  
1/1/2015                              30y
1/1/2015                              303

我想要基于日期的记录(想要多个记录)。有没有办法可以为这种类型的需求写一个查询。谢谢

2 个答案:

答案 0 :(得分:0)

这是一个支点。在MySQL中,您可以使用条件聚合:

select rp.date,
       max(case when returnperiod = 10 then value end) as rp10_value,
       . . .
from return_period rp
group by rp.date;

编辑:

我看到你有重复。同样的想法适用,但您需要包含序列号:

select rp.date,
       max(case when returnperiod = 10 then value end) as rp10_value,
       . . .
from (select rp.*,
             row_number() over (partition by date, returnperiod order by date) as seqnum
      from return_period rp
     ) rp
group by rp.date, seqnum;

答案 1 :(得分:0)

select date,
case when rp=10 then value else null end as Rp10_Value,
case when rp=10 then value else null end as Rp20_Value,
case when rp=10 then value else null end as Rp30_Value

from
(
SELECT date, value,  ReturnPeriod
FROM Table2 where ReturnPeriod=10
union all
SELECT date, value,  ReturnPeriod
FROM Table2 where ReturnPeriod=20
union all
SELECT date, value,  ReturnPeriod
FROM Table2 where ReturnPeriod=30
) ;