我有一个名为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 Abc
6 CD DD1 6363 Sde
7 TT QQ6 7635 Sde
8 AB DD1 9998 Dfr
9 AB DD1 9998 Red
1)列出他们 我想列出IntID列中具有重复值的记录。结果中的每条记录都应该有:
我要找的结果如下:
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中)中执行此操作?
答案 0 :(得分:2)
2号。)
select area, type, count(*) from servicerequest group by area, type
答案 1 :(得分:1)
首先,我们需要找到哪些值是重复的,然后是具有这些IntID值的行,按区域&获取我们的分组。键入,然后将该信息与各行组合。公用表表达式(CTE)简化了这类工作。在此示例中,i
将引用第一个子查询,其中我们找到哪个IntID有重复项,g
是我们获取组信息的第二个。{/ p>
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
现在我们知道如何查找重复值,我们可以将其应用于第二个问题,使其成为一项相当简单的任务。
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