PSQL新手..我有一张有主键和两个时间戳的表
ID Start_date end_date
100 9/4/14 14:53 9/4/14 14:56
100 4/24/13 12:49 4/24/13 14:08
100 9/25/15 11:06 9/25/15 11:14
101 2/7/15 12:05 2/7/15 12:09
101 2/4/13 17:18 Null
102 12/6/12 13:22 NULL
102 12/6/12 13:28 NULL
102 12/6/12 13:36 12/12/12 8:38
我希望输出是每个ID的最小日期
ID Start_date end_date
100 4/24/13 12:49 4/24/13 14:08
101 2/4/13 17:18 Null
102 12/6/12 13:22 NULL
我有以下查询:
SELECT distinct ID,
min(end_date) ,
min(Start_date)
from x
group by ID.
这会导致错误的相应值。我该怎么做呢?
答案 0 :(得分:0)
使用ROW_NUMBER
:
SELECT
ID,
Start_date,
end_date
FROM (
SELECT *, ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Start_date) AS rn FROM x
) AS t
WHERE rn = 1;