繁体   English   中英

根据日期对表的数据进行分组,并为MYsql中的值构建多列表

[英]Group the data of a table based on the date and build the multicolumns table for values in MYsql

真的被这个SQL程序卡住了一个多星期。 我有一个包含三列的表格,一列显示 ID,一列显示日期,一列显示温度。 这是表的代码:

Create table  temperature (id int, date varchar(255), temperature float(2, 1));

 insert into temperature (id, date, temperature) values ('1', '2012-01-01 6:00:00',  '8.9');
 insert into temperature (id, date,  temperature) values ('1', '2012-01-01 6:15:00',  '8.5');
 insert into temperature (id, date,  temperature) values ('1', '2012-01-01 6:30:00',  '6.2');
 insert into temperature (id, date,  temperature) values ('1', '2012-01-01 6:45:00',  '8.6');
 insert into temperature(id, date,  temperature) values ('3', '2012-01-02 6:00:00',  '9.1');
 insert into temperature (id, date,  temperature) values ('3', '2012-01-01 6:15:00',  '8.9');
 insert into temperature (id, date,  temperature) values ('4', '2012-01-01 6:00:00',  '8.5');
 insert into temperature (id, date,  temperature) values ('4', '2012-01-01 6:15:00',  '6.2');
 insert into temperature (id, date,  temperature) values ('4', '2012-01-01 6:30:00',  '8.6');
 insert into temperature (id, date,  temperature) values ('2', '2012-01-01 6:00:00',  '9.1');
 SELECT * FROM temperature;

这是表格的数字:

在此处输入图像描述

每行都有一个非常具体的时间。 我想在一列中显示每个id和每个时间段的温度。

例如,对于 id=1,我们有四个温度。 然后我们有 4 个值并将它们按顺序放在 val1-val4 中。 对于 id=3,我们有两天有一个数字,每天我们考虑一个列表,对于 id=4,我们一天有三个数字,对于 id=2,我们一天只有一个数字。

值的最大长度为 4(在我的实际应用中为 96)。

最后要这张表(图中有错字,第二个id=3的val2应该是8.9):

在此处输入图像描述

我使用了group_concat ,但是,它将它们保存为字符串。 此外,我正在使用date_format(from_unixtime(date), '%Y-%m-%d')将日期更改为 YYYY-MM-DD。 我使用的代码是

   SELECT id, 
          date_format(from_unixtime(date), '%Y-%d-%m') as date, 
          GROUP_CONCAT(value) as Value group by id, date
    FROM temperature;  
  

注意:在我的真实数据库中,值的最大长度是 96,我有超过 1000 万行,使用CASEWHEN效率不高。

如果你的MySQL版本支持 windows function 你可以使用:

with cte as (
select id, date, temperature,row_number() over(partition by id order by `date`) rownum
from temperature
) 
select id,date(`date`),max(case when rownum=1 then cte.temperature else null end) as val1,
                       max(case when rownum=2 then cte.temperature else null end) as val2,
                       max(case when rownum=3 then cte.temperature else null end) as val3,
                       max(case when rownum=4 then cte.temperature else null end) as val4
from cte
group by id,date(`date`);

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM