检索列中的重复项,列出并计数它们(DB2上的SQL)
我有一张名为ServiceRequest的表。请参阅下面的一些记录和列检索列中的重复项,列出并计数它们(DB2上的SQL),sql,count,group-by,db2,duplicates,Sql,Count,Group By,Db2,Duplicates,我有一张名为ServiceRequest的表。请参阅下面的一些记录和列 RowID Type Area IntID OwnerBussUnit 1 AB DD1 1234 Abc 2 AB EE2 7635 Abc 3 CD DD1 1234 Bde 4 FE FF3 2423 Gte 5 AB DD1 1234
RowID Type Area IntID OwnerBussUnit
1 AB DD1 1234 Abc
2 AB EE2 7635 Abc
3 CD DD1 1234 Bde
4 FE FF3 2423 Gte
5 AB DD1 1234 Abc
6 CD DD1 6363 Sde
7 TT QQ6 7635 Sde
8 AB DD1 9998 Dfr
9 AB DD1 9998 Red
1) 列出它们 我想在IntID列中列出具有重复值的记录。结果中的每个记录应具有:
- #IntID:重复IntID的计数次数(因此可以超过两次)
- #GroupBy:列“Type”和“Area”组合计算重复IntID的次数
- 同一所有者;其中,在类型和区域分组中,OwnerBussUnit具有相同的值
- 扩散所有者;其中,在类型和区域分组中,OwnerBussUnit按IntID、RowID的值顺序不同
IntID RowID Type Area #IntID #GroupBy SameOwner DiffOwner
1234 1 AB DD1 3 2 Yes No
1234 3 CD DD1 3 1 Yes No
1234 5 AB DD1 3 2 Yes No
7635 2 AB EE2 2 1 No Yes
7635 7 TT OO6 2 1 No Yes
9998 8 AB DD1 2 2 No Yes
9998 9 AB DD1 2 2 No Yes
2) 数一数 计数按类型和区域分组的重复IntID。 因此,结果如下所示:
Type Area #IntID
AB DD1 4
CD DD1 1
AB EE2 1
TT OO6 1
如何在SQL(DB2)中实现这一点
1)
首先,我们需要找到哪些值是重复的,然后是具有这些IntID值的行的数量,按区域和类型进行分组,然后将这些信息与单独的行相结合。公共表表达式(CTE)简化了这样的阶段中的工作。在本例中,i
将引用第一个子查询,在该子查询中,我们可以找到哪些IntID具有DUP,而g
将引用第二个子查询,在该子查询中,我们可以获得组的信息
with i as
( select IntId,
count(*) as tally
from ServiceRequest
group by IntID
having count(*)>1
), g as
( select j.IntId, j.Area, j.Type,
count(*) as tally,
count(distinct j.OwnerBussUnit) as owners
from ServiceRequest j
join i on i.IntID=j.IntID
group by j.IntId, j.Area, j.Type
)
select x.IntID, x.RowID, x.Type, x.Area,
i.tally as "#IntID"
g.tally as "#GroupBy",
case owners when 1 then 'Yes'
else 'No'
end as SameOwner,
case owners when 1 then 'No'
else 'Yes'
end as DiffOwner
from ServiceRequest x
join i on i.IntID = x.IntID
join g on g.IntID = x.IntID
and g.Type = x.Type
and g.Area = x.Area
Order by x.IntID, x.RowID
2)
现在我们知道了如何找到重复的值,我们可以将其应用于第二个问题,使之成为一项相当简单的任务
with i as
( select IntId,
count(*) as tally
from ServiceRequest
group by IntID
having count(*)>1
)
select x.Type, x.Area,
count(*) as "#IntID"
from ServiceRequest x
join i on i.IntID = x.IntID
group by Area, Type
order by Area, Type
到目前为止您尝试了什么?OP要求只处理IntID中有重复项的行。您的查询将错误地包括第4行和第6行。
with i as
( select IntId,
count(*) as tally
from ServiceRequest
group by IntID
having count(*)>1
)
select x.Type, x.Area,
count(*) as "#IntID"
from ServiceRequest x
join i on i.IntID = x.IntID
group by Area, Type
order by Area, Type