在一列上选择distinct,并考虑另一列

3npbholx  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(396)

我有

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

每个“号码”我只想要一次,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
c6ubokkw

c6ubokkw1#

如果列数多于此列,则需要关联子查询 group bymax() 足以达到期望的结果:

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

不过,最新版本还有一个选项可以通过使用 row_number() .

sd2nnvve

sd2nnvve2#

试着用一个简单的 GROUP BY 查询:

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

在更新的问题/查询的上下文中:

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;
kzipqqlq

kzipqqlq3#

另一种方法是使用自联接:

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

相关问题