![](/img/trans.png)
[英]SQL Server - Select Distinct of two columns, where the distinct column selected has a maximum value based on two other columns
[英]SQL Select a distinct row based on two columns which has min value in third column
編輯:我正在使用PostgresSQL
我的查詢需要返回id列和type列的所有唯一行。 當有多個具有相同ID的行並鍵入時,它將返回時間列中值最小的行。
SELECT id, type, value FROM TableName
GROUP BY MIN(time)
ORDER BY id ASC, type ASC
這是我到目前為止的內容,但是我覺得我使用錯誤的方式使用GROUP BY
我認為您可以使用ROW_NUMBER
來標記id和type的每個組合中的行,其中最小的時間為rn = 1 ,然后使用WHERE子句過濾表:
SELECT id, type, value FROM
(SELECT id, type, value,
ROW_NUMBER() OVER(PARTITION BY id, type ORDER BY time) AS rn
FROM TableName) a
WHERE rn = 1
Postgres支持distinct on
。 通常,這是執行所需操作的最有效方法:
SELECT DISTINCT ON (id, type) id, type, value
FROM TableName
ORDER BY id, type, time ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.