MYSQL to get a diff in value in the same column but hour field is difference in the same table

junjoi :

How to get a different value in the same table, data is changed based on hours

Table Structure

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

the out result is looking for

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

Same as for other countries.

GMB :

In MySQL 8.0, you can use window functions:

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

If you want to eliminate the first row per group, then you can use a subquery:

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

In earlier versions, you could self-join the table:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=346657&siteId=1