MYSQLは同じ列に値の差分を取得するが、時間のフィールドは、同じテーブルの差であります

junjoi:

同じテーブルに別の値を取得する方法、データを時間に基づいて変更されます

テーブル構造

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

他の国と同じ。

GMB:

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=347558&siteId=1