简体   繁体   English

SELECT DISTINCT在一个列上考虑另一列

[英]SELECT DISTINCT on one column considering another column

I have 我有

    Id          Number
----------- -----------
950         20213666062
951         20213666062

I want only one time each "number", the one with the highest Id: 我只希望每个“数字”一次,其ID最高:

    Id          Number
----------- -----------
951         20213666062

SELECT
rarN.intIdRARNomina AS Id,
rarN.chrCUIL AS Number           
FROM dbo.PVN_RAR p
        INNER JOIN dbo.PVN_RARNomina rarN ON p.intIdRAR = rarN.intIdRAR
        INNER JOIN PISCYS.dbo.SYA_UltimosContratoCliente uc ON p.intNroContrato = uc.intNroContrato
WHERE
        p.intIdRAR = 4639

Try using a simple GROUP BY query: 尝试使用简单的GROUP BY查询:

SELECT MAX(Id) AS Id, Number
FROM yourTable
GROUP BY Number;

In the context of your updated question/query: 在您更新的问题/查询的上下文中:

SELECT
    MAX(rarN.intIdRARNomina) AS Id,
    rarN.chrCUIL AS Number
FROM dbo.PVN_RAR p
INNER JOIN dbo.PVN_RARNomina rarN
    ON p.intIdRAR = rarN.intIdRAR
INNER JOIN PISCYS.dbo.SYA_UltimosContratoCliente uc
    ON p.intNroContrato = uc.intNroContrato
WHERE
    p.intIdRAR = 4639
GROUP BY
    Number;

You need correlated subquery if you have a more columns than this else only group by with max() is enough to achieve the desire result : 如果您的列多于此,则需要相关子查询,否则仅使用max() group by才能达到所需的结果:

select t.*
from table t
where t.id = (select max(t1.id) from table t1 where t1.Number = t.Number);

However, Latest version has one more option to achieve this by using row_number() . 但是,最新版本通过使用row_number()实现此目的。

Another alternative is to use a self join: 另一种选择是使用自我联接:

select t.*
from table t
inner join (select max(id) as DID, number from table group by number) t2
on t.ID = t2.DID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM