假设我有一个包含foo,bar,creatationdate和data列的数据库。
我需要的是一个查询,它针对foo和bar的每种唯一组合查询已创建的第一行(即,creationdate在最低位置)。
例如,对于以下行:
+-----+-----+--------------+----------------+
| foo | bar | creationdate | data |
+-----+-----+--------------+----------------+
| abc | def | 31.12.2019 | some data |
+-----+-----+--------------+----------------+
| abc | def | 01.05.2020 | other data |
+-----+-----+--------------+----------------+
| ghi | jkl | 04.05.2020 | more data |
+-----+-----+--------------+----------------+
| ghi | jkl | 05.05.2020 | even more data |
+-----+-----+--------------+----------------+
然后所需的输出是:
+-----+-----+--------------+----------------+
| abc | def | 31.12.2019 | some data |
+-----+-----+--------------+----------------+
| ghi | jkl | 04.05.2020 | more data |
+-----+-----+--------------+----------------+
将给我想要的结果的SQL查询是什么?我正在使用Postgres。
答案 0 :(得分:3)
通常使用Postgres中专有的distinct on ()
select distinct on (foo,bar) foo, bar, creationdate, data
from the_table
order by foo,bar,creationdate;
答案 1 :(得分:2)
尝试以下操作,可以使用窗口功能row_number()
来实现。您可能需要更改creationDate
格式。这是demo。
select
foo,
bar,
creationDate
from
(
select
foo,
bar,
creationDate,
row_number() over (partition by foo, bar order by creationDate) as rnk
from yourTable
) val
where rnk = 1