我正在使用 SQL Server 2014 并有一個這樣的表:
PK ContactID Tele Mob Land Email Txt
1 10 1 0 1 1 1
2 10 0 1 0 0 1
3 12 1 3 1 1 1
期望的結果是:
PK ContactID Tele Mob Land Email Txt
2 10 0 1 0 0 1
3 12 1 3 1 1 1
但是,如果我執行 GroupBy \ Max:
SELECT MAX(PK) AS PK, ContactID, Tele, Mob, Land, Email, Txt
FROM Contacts
GROUP BY ContactID, Tele, Mob, Land, Email, Txt
我剛剛收到:
PK ContactID Tele Mob Land Email Txt
1 10 1 0 1 1 1
2 10 0 1 0 0 1
3 12 1 3 1 1 1
我該如何修改才能給我想要的結果?
uj5u.com熱心網友回復:
如果我理解正確,您可以嘗試使用ROW_NUMBER視窗功能來制作它。
SELECT *
FROM (
SELECT *,ROW_NUMBER() OVER(PARTITION BY ContactID ORDER BY PK DESC) rn
FROM Contacts
) t1
WHERE rn = 1
uj5u.com熱心網友回復:
ContactId 的最后一個 PK 行,使用top with ties
SELECT top(1) with ties *
FROM Contacts
ORDER BY row_number() over(partition by ContactID order by PK desc)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/474595.html
