我有两张桌子
table1:itemTbale
table2:itemDetails
itemTable contain
id | itemName
itemDetails
id | itemID | price | details
表可能包含这样的数据
id | itemName
1 Vechile
2 Fruits
id | itemID | price | details
1 1 80$ bla bla
2 1 150$ bla bla bla
3 1 200$ bla bla
4 2 5$ ..
5 2 8$ ..bla
6 2 7$ bla..
现在我必须为每个itemID选择最高项目详细信息
LIKE
id | itemID | price | details |itemName
1 1 80$ bla bla Vechile
4 2 5$ .. Fruits.
我对查询感到困惑。请帮助我 提前谢谢。
答案 0 :(得分:2)
;WITH MyCTE AS
(
SELECT D.id,
D.itemID,
D.price,
D.details,
T.itemName,
ROW_NUMBER() OVER(PARTITION BY D.itemID ORDER BY D.id) AS row_num
FROM itemTable T
JOIN itemDetails D
ON T.id = D.itemId
)
SELECT id,
itemID,
price,
details,
itemName
FROM MyCTE
WHERE row_num = 1