MYSQL在同一列中获取值的差异,但小时字段在同一表中是差异



如何在同一个表中获得不同的值,数据根据小时进行更改

表格结构

Current Table
country | hour | date | total
China | 22 | 18-March-2020 | 25777
China | 23 | 18-March-2020 | 35477
China | 24 | 18-March-2020 | 45777
India| 22 | 18-March-2020 | 4547
India | 23 | 18-March-2020 | 5477
India | 24 | 18-March-2020 | 6478

结果是寻找

China | 23 | 35477 - 25777
China | 24 | 45777-35477

与其他国家相同。

在MySQL 8.0中,您可以使用窗口函数:

select
t.*,
concat(total, ' - ', lag(total) over(partition by country, date order by hour)) info
from mytable

如果您想消除每个组的第一行,那么您可以使用子查询:

select *
from (
select
t.*,
concat(total, ' - ', lag(total) over(partition by country, date order by hour)) info
from mytable
) t
where info is not null

在早期版本中,您可以自行加入表格:

select t.*, concat(t.total, ' - ', tlag.total) info
from mytable t
inner join mytable tlag 
on tlag.country = t.country and tlag.date = t.date and tlag.hour = t.hour - 1

最新更新