mysql - Compare values from strings for date=n with date=n-1

℡╲_俬逩灬. 提交于 2021-02-08 12:01:33

问题


I have a dataset like:

id | country | date       | rank   | sport
--------------------------------------------
1  | US      | 2000-01-30 | 1      | tennis
2  | BE      | 2000-01-30 | 2      | tennis
3  | UK      | 2000-01-30 | 3      | tennis
4  | UK      | 2000-01-30 | 1      | golf
5  | US      | 2000-01-30 | 2      | golf
6  | FR      | 2000-01-30 | 3      | golf
7  | UK      | 2000-01-31 | 1      | tennis
8  | US      | 2000-01-31 | 2      | tennis
9  | FR      | 2000-01-31 | 3      | tennis
10 | UK      | 2000-01-31 | 1      | golf
11 | US      | 2000-01-31 | 2      | golf
12 | FR      | 2000-01-31 | 3      | golf

I'd like to have a result like:

date          country   sport     rank    rank-1   rankDiff
2000-01-31    UK        TENNIS    1       3        2
2000-01-31    US        TENNIS    2       1        -1
....

How do I arrange this? Selecting the current date is not the problem of couse, but comparing the current date with the previous is not so easy...

SELECT * FROM table WHERE date = '2000-01-31'

Hope you could help me out!


回答1:


If you are running MySQL 8.0, you can use lag():

select
    dte,
    country,
    sport,
    rnk,
    lag(rnk) over(partition by country, sport order by dte) rnk_1,
    lag(rnk) over(partition by country, sport order by dte) - rnk rank_diff
from mytable

If you need to filter on a given date, you can do it in an outer query:

select *
from (
    select
        dte,
        country,
        sport,
        rnk,
        lag(rnk) over(partition by country, sport order by dte) rnk_1,
        lag(rnk) over(partition by country, sport order by dte) - rnk rank_diff
    from mytable
) t
where dte = '2000-01-31'

Please note that date and rank are names of MySQL functions, hence not a good choice for column names. I renamed the columns in the query.




回答2:


SELECT x.date
     , x.country
     , x.sport
     , x.rank
     , y.rank prev
     , y.rank-x.rank delta 
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.country = x.country 
   AND y.sport = x.sport 
   AND y.date = '2000-01-30' 
 WHERE x.date = '2000-01-31';


来源:https://stackoverflow.com/questions/59544520/mysql-compare-values-from-strings-for-date-n-with-date-n-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!