我在表格中有以下数据:
ORDERID, PRODUCT, QUANTITY
1, potatoes, 10
1, oranges, 20
2, apples, 10
2, oranges, 15
3, pears, 20
3, peaches, 12
我想查询该表以过滤掉重复的产品(例如橙子),只获取最新的(更高的ORDERID)值。这应该导致:
ORDERID, PRODUCT, QUANTITY
1, potatoes, 10
2, apples, 10
2, oranges, 15
3, pears, 20
3, peaches, 12
答案 0 :(得分:3)
select *
from (select t.*
,row_number () over (partition by PRODUCT order by ORDERID desc) as rn
from mytable t
)
where rn = 1
答案 1 :(得分:1)
@Dudu给出的答案的替代方法是查询子查询以查找每个产品的最大订单ID,然后将其连接回原始表格以限制您想要查看的记录。
SELECT t1.ORDERID,
t1.PRODUCT,
t1.QUANTITY
FROM yourTable t1
INNER JOIN
(
SELECT PRODUCT, MAX(ORDERID) AS MAX_ORDERID
FROM yourTable
GROUP BY PRODUCT
) t2
ON t1.PRODUCT = t2.PRODUCT AND
t1.ORDERID = t2.MAX_ORDERID