如何在MySQL Workbench中从两列中获取最新日期?

问题描述 投票:0回答:2

我有一个表是这样的。

ID   B     C      date01        date02
11  xxx   xxxx   2020-05-01    2020-05-02
11  xxx   xxxx   2020-05-01    2020-05-03
11  xxx   xxxx   2020-05-01    2020-05-01
11  xxx   xxxx   2020-02-03    2020-02-08
11  xxx   xxxx   2020-02-03    2020-02-31
22  xxx   xxxx   2020-05-01    2020-05-02
22  xxx   xxxx   2020-05-01    2020-05-03
22  xxx   xxxx   2020-05-01    2020-05-01
22  xxx   xxxx   2020-02-03    2020-02-08
22  xxx   xxxx   2020-02-03    2020-02-31

我想返回所有的东西 但每个ID的最新日期是date01 & date02, 预期输出:

11  xxx   xxxx   2020-05-01    2020-05-03
22  xxx   xxxx   2020-05-01    2020-05-03

我试了一下

SELECT 
    ID, B, C, date01, date02
FROM 
    table
order by date01 desc
GROUP BY ID 

但它给我的是: Error Code: 1064. You have an error in your SQL syntax

我是个SQL新手,还在学习,我做错了什么?谁能帮我解决这个问题?先谢谢你了。

更新:我忘了一个约束条件,一些 date01 晚于 date02,我只想知道日期在哪里 date01 早于 date02.

mysql sql mysql-workbench mysql-error-1064
2个回答
0
投票

你想通过 "汇总 "来 id. 您可以使用 MAX() 来获取最新的日期,如。

select
  id, 
  max(b),
  max(c),
  max(date01),
  max(date02)
from t
group by id

0
投票

一种方法是相关的子查询。

select t.*
from t
where greatest(t.date1, t.date2) = (select max(greatest(t1.date1, t2.date2))
                                    from t t2
                                    where t2.id = t.id
                                   );

另一种方法是窗口函数。

select t.*
from (select t.*,
             row_number() over (partition by id order by greatest(t1.date1, t2.date2) desc) as seqnum
      from t
     ) t
where seqnum = 1;

0
投票

在MySQL 8+,我会在这里使用分析函数。

WITH cte AS (
    SELECT *, MAX(date01) OVER (PARTITION BY ID) max_date01,
        MAX(date02) OVER (PARTITION BY ID) max_date02
    FROM yourTable
)

SELECT *
FROM yourTable
WHERE date01 = max_date01 AND date02 = max_date02;
© www.soinside.com 2019 - 2024. All rights reserved.