通过postgresql从组中获取最小日期

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

请帮助我进行 postgresql 查询

我有包含数据的表格:

market  certificate_id   date
K010    vwv              10.12.2023
K010    cert1            12.12.2023
K054    vwv              14.12.2023
K054    cert1            20.01.2024

我想使用 cert_id 按市场选择最短日期

我已经尝试过这个查询

但它正在提供所有市场

还有这个查询

它给出了市场 K010 的最小日期,但没有给出市场 K054,对于 K054,它给出了日期中的最大值

我想通过其证书 ID 获取市场的第一个最短日期 像这样:

market  certificate_id   date
K010    vwv              10.12.2023
K054    vwv              14.12.2023

有人可以帮忙吗?

sql postgresql group-by min
3个回答
0
投票

使用 row_number() + 过滤器 rn=1:

select market,  certificate_id,   date
from 
(
select market,  certificate_id,   date,
       row_number() over(partition by market order by date) rn
) s 
where rn = 1

0
投票

您可以使用窗口函数来做到这一点

row_number()

select *
from (
  select *, row_number() over (partition by market order by audit_ending) as rn
  from mytable
) as s
where rn = 1

0
投票

你的

distinct on
几乎是正确的:

select distinct on(store_code) store_code,certificate_id,audit_ending
from measure_app_scalemeasurement
group by store_code
order by store_code,date;
© www.soinside.com 2019 - 2024. All rights reserved.