获取MySQL中最早或最新的行详细信息

时间:2020-02-28 22:22:50

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

我有一张这样的桌子。它的工作方式是每天结算一次,以确保帐户是最新的。

+------+------------+-------------+
| 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  |
+------+------------+-------------+

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

1 个答案:

答案 0 :(得分:0)

如果运行的是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
相关问题