首页 > 解决方案 > 选择具有多个非不同父级的重复列

问题描述

下面是图 1 中显示的我的表结构

我正在创建一个查询,它会给我一个像 Image 2 这样的结果

我创建了以下查询,但它没有给我预期的结果

select v.attributeCd , v.parentObject_id  
from Mapping v where v.parentObject_id in ( 
    select distinct(v1.parentObject_id) 
    from Mapping v1)   
group by v.attributeCd , v.parentObject_id 
having count(v.attributeCd) > 2 order by attributeCd  

标签: sql-server

解决方案


正如 GMB 提到的,您可以进行窗口计数。

DECLARE @Mapping AS TABLE
(
    attributeCd         VARCHAR(20)
    ,parentObject_id    INT
)

INSERT INTO @Mapping 
(
    attributeCd 
    ,parentObject_id
)
VALUES
 ('AccountNumber',218)
,('AdditionalWeeks',46)
,('AdminCharges',29)
,('AdminCharges',230)
,('AgeCategoryCd',56)
,('AgeCategoryCd',155)
,('AgentDivisionCd',118)
,('AgentNum',275)
,('AgentNum',445)
,('EntryAge',4)
,('ExpiryDt',181)
,('ExpiryDt',184)
,('ExpiryDt',186)

select  attributeCd ,parentObject_id
FROM
    (select 
        attributeCd
        ,parentObject_id
        ,CNT                = COUNT(*) OVER(PARTITION BY attributeCd)
    from 
        @Mapping) AS V
WHERE
    V.CNT > 1
ORDER BY 
    attributeCd

首先了解子查询的结果,以获得查询的全貌。

我希望这有帮助。


推荐阅读