postgresql Posgresql为特定列选择具有最小值的行

wfauudbj  于 2023-05-17  发布在  PostgreSQL
关注(0)|答案(2)|浏览(241)

我有下表:

ID     SORT_ID     MY_DATE       USER_ID
10       1         01/01/2023      1
11       2         01/09/2023      1
13       3         15/08/2023      1
14       4         10/12/2023      1

我想选择(对于USER_ID = 1)具有最低SORT_ID的行的日期,即具有SORT_ID = 1ID = 10的行
我尝试了这个查询,但它返回了最高的(行与:SORT_ID = 4 and ID = 14

SELECT DISTINCT ON (USER_ID)
MY_DATE 
FROM MY_TABLE where USER_ID = 1
ORDER BY USER_ID;

你有什么办法来调整我的选择,以获得最低行(USER_ID = 1 AND SORT_ID = 1 AND ID = 10)动态

68bkxrlz

68bkxrlz1#

您只需要更改查询中的order by子句。

SELECT DISTINCT ON (USER_ID)
MY_DATE 
FROM MY_TABLE where USER_ID = 1
ORDER BY USER_ID,SORT_ID;
cnjp1d6j

cnjp1d6j2#

您可以简单地:

SELECT *
FROM MY_TABLE 
WHERE USER_ID = 1
ORDER BY SORT_ID
LIMIT 1

或者使用group bymin()
首先获取用户的最小SORT_ID:

select USER_ID, min(SORT_ID) as min_id
from MY_TABLE
where USER_ID = 1
group by USER_ID

然后将其与表连接以获得预期结果:

select t.*
from MY_TABLE t
inner join (
  select USER_ID, min(SORT_ID) as min_SORT_ID
  from MY_TABLE
  where USER_ID = 1
  group by USER_ID
) as s on s.USER_ID = t.USER_ID and s.min_SORT_ID = t.SORT_ID
where t.USER_ID = 1

Demo here

相关问题