使用子查询分组并按 2 列分组,返回重复项的所有列

问题描述 投票:0回答:1

我有一个查询,它将根据子查询分组返回所有重复行。 分组依据仅使用 1 列。

select *
from "*original_item_master" i
where "ItemStatus" != 'Inactive'  and 
 "ManufacturePartNBR" in (
    select "ManufacturePartNBR"
    from "*original_item_master" i
    group by "ManufacturePartNBR"
    having count (*) > 1 )
order by "ManufacturePartNBR" asc

我需要使用 2 列进行分组,但它不起作用。 这是我尝试过的。

select *
from "*original_item_master" i
where "ItemStatus" != 'Inactive'  and 
  "ManufacturePartNBR" , "ManufactureNM" in (
    select "ManufacturePartNBR", "ManufactureNM" 
    from "*original_item_master" i
    group by "ManufacturePartNBR", "ManufactureNM" 
    having count (*) > 1 )
order by "ManufacturePartNBR" asc 
sql group-by
1个回答
0
投票

您可以使用

EXISTS
子选择,例如

select *
from "*original_item_master" i
where "ItemStatus" != 'Inactive'  and 
  exists (
    select 1 
    from "*original_item_master" i2
    where i."ManufacturePartNBR" = i2."ManufacturePartNBR" and i."ManufactureNM" = i2."ManufactureNM"
    group by i2."ManufacturePartNBR", i2."ManufactureNM" 
    having count (*) > 1 )
order by "ManufacturePartNBR" asc 

这是一个好主意,因为

EXISTS
搜索第一个匹配项,因此最好使用它而不是
IN
。或者,您可以:

select *
from "*original_item_master" i
where "ItemStatus" != 'Inactive'  and 
  ("ManufacturePartNBR" , "ManufactureNM") in (
    select "ManufacturePartNBR", "ManufactureNM" 
    from "*original_item_master" i
    group by "ManufacturePartNBR", "ManufactureNM" 
    having count (*) > 1 )
order by "ManufacturePartNBR" asc 

但这可能会降低性能。

© www.soinside.com 2019 - 2024. All rights reserved.