SQL组由最大不需要结果

发布于 2025-01-26 01:49:50 字数 880 浏览 3 评论 0原文

我正在使用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 

如何修改以给我预期的结果?

I'm using SQL Server 2014 and have a table like this:

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  

The desired result is:

PK    ContactID  Tele    Mob   Land  Email  Txt
2       10        0       1     0     0      1
3       12        1       3     1     1      1 

However, if I perform a GroupBy \ Max:

SELECT        MAX(PK) AS PK, ContactID, Tele, Mob, Land, Email, Txt
FROM            Contacts
GROUP BY ContactID, Tele, Mob, Land, Email, Txt

I'm just receiving:

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 

How do I modify to give me the desired results?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

篱下浅笙歌 2025-02-02 01:49:50

如果我正确理解,您可以尝试使用row_number窗口函数来制作它。

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

If I understand correctly, you can try to use ROW_NUMBER window function to make it.

SELECT *
FROM (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY ContactID ORDER BY PK DESC) rn
    FROM Contacts
) t1
WHERE rn = 1
多彩岁月 2025-02-02 01:49:50

最后一个由pk行使用ties的contactID进行contactid

SELECT top(1) with ties *
FROM Contacts
ORDER BY row_number() over(partition by ContactID order by PK desc)

The last by PK row for a ContactId using top with ties

SELECT top(1) with ties *
FROM Contacts
ORDER BY row_number() over(partition by ContactID order by PK desc)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文