SQL 查询以查找特定月份的最后一个事件
SQL Query to find the last event in a particular month
我正在尝试查询最后一个条目在一月份(01/01/2020 到 31/01/2020)内的 ID。
数据如下
ID DATE
123 25/01/2020
123 27/01/2020
123 30/01/2020
123 02/02/2020
456 17/01/2020
456 18/01/2020
456 19/01/2020
456 22/01/2020
789 30/01/2020
789 01/01/2020
654 03/01/2020
654 08/01/2020
654 10/01/2020
654 25/01/2020
预期输出
ID DATE
456 22/01/2020
654 25/01/2020
谢谢
您可以使用 group by
和 having
:
select id, max(date)
from t
group by id
having max(date) >= date '2020-01-01' and
max(date) < date '2020-02-01'
我正在尝试查询最后一个条目在一月份(01/01/2020 到 31/01/2020)内的 ID。
数据如下
ID DATE
123 25/01/2020
123 27/01/2020
123 30/01/2020
123 02/02/2020
456 17/01/2020
456 18/01/2020
456 19/01/2020
456 22/01/2020
789 30/01/2020
789 01/01/2020
654 03/01/2020
654 08/01/2020
654 10/01/2020
654 25/01/2020
预期输出
ID DATE
456 22/01/2020
654 25/01/2020
谢谢
您可以使用 group by
和 having
:
select id, max(date)
from t
group by id
having max(date) >= date '2020-01-01' and
max(date) < date '2020-02-01'