【问题标题】:Get Earliest or Latest Date of Row Detail in MySQL [duplicate]在MySQL中获取行详细信息的最早或最晚日期[重复]
【发布时间】:2020-06-13 01:07:18
【问题描述】:

我有一张这样的桌子。它的工作方式是每天进行计费以确保帐户是最新的。

+------+------------+-------------+
| ID   | AcctType   | BillingDate |
+------+------------+-------------+
| 100  | Individual | 2020-01-01  |
| 100  | Individual | 2020-01-02  |
| 100  | Individual | 2020-01-03  |
| 101  | Group      | 2020-01-01  |
| 101  | Group      | 2020-01-02  |
| 101  | Individual | 2020-01-01  |
+------+------------+-------------+

我需要按 ID 查找每个计划的第一个和最后一个 AcctType,因为 AcctType 可以更改。我正在使用 MySQL,select ID, AcctType, min(BillingDate) from table group by ID 的聚合将不起作用,因为 AcctType 将返回与 ID 关联的随机值。如何通过 ID 可靠地获取最新和最早的 AcctType?使用 5.6 版。

【问题讨论】:

  • 你运行的是哪个版本的 MySQL?

标签: mysql sql date greatest-n-per-group


【解决方案1】:

如果您运行的是 MySQL 8.0,则可以为此使用窗口函数:

select distinct
    id,
    first_value(acctType) over(
        partition by id 
        order by billingDate 
        rows between unbounded preceding and unbounded following
    ) firstAccType,
    last_value(acctType) over(
        partition by id 
        order by billingDate 
        rows between unbounded preceding and unbounded following
    ) lastAccType
from mytable

这会为每个id 生成一条记录,列中的第一个和最后一个值为accType

在早期版本中,使用相关子查询可能是实现相同结果的最简单解决方案:

select distinct 
    id,
    (
        select t1.accType 
        from mytable t1 
        where t1.id = t.id 
        order by billingDate asc
        limit 1
    ) firstAccType,
    (
        select t1.accType 
        from mytable t1 
        where t1.id = t.id 
        order by billingDate desc
        limit 1
    ) lastAccType
from mytable

【讨论】:

  • 抱歉这里使用的是旧版本。 5.6
  • @noobsmcgoobs:我用早期版本的解决方案更新了我的答案。
猜你喜欢
  • 2021-09-29
  • 1970-01-01
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 2021-06-29
  • 1970-01-01
  • 2020-02-04
相关资源
最近更新 更多