SQL Group by Max 不是想要的结果

SQL Group by Max not desired results

我正在使用 SQL Server 2014 并且 table 是这样的:

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 

如何修改才能得到我想要的结果?

如果我没理解错的话,你可以尝试用ROW_NUMBERwindow函数来制作

SELECT *
FROM (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY ContactID ORDER BY PK DESC) rn
    FROM Contacts
) t1
WHERE rn = 1

使用 top with ties

的 ContactId 的最后一个主键行
SELECT top(1) with ties *
FROM Contacts
ORDER BY row_number() over(partition by ContactID order by PK desc)