我的数据表示我的数据,其中col1是recID(int),col2是版本(varchar),col3是补丁(int)。
此表格中有重复项(参见36,37):
recID version patch
32 5.1.4 434 -
36 5.1.4 434 p2
37 5.1.4 434 p2
我使用此查询给我重复:
select recID,
count(Version) as Count,
Version
from Test
group by Version
having count > 1;
输出:
recID Count Version Patch
32 3 434 -
如何修复此查询?我想列出recID,这是错误的,因为recID不是一个dup,但是有一个空值。
但我正在寻找的是给我一些重复的版本并以这种方式列出(如果可能的话) 预期产出:
recID Count Version Patch
32 1 5.1.4 434 -
36 2 5.1.4 434 p2
37 - 5.1.4 434 p2
答案 0 :(得分:0)
您可以使用变量获得预期的输出
select recID, version, patch,
case when @prevValue = version
then @cnt:=@cnt+1
else @cnt:=0
end as DupCount,
@prevValue:=version as var_version
FROM Table1, ( select @prevValue := NULL , @cnt:=0 ) t
order by version
答案 1 :(得分:0)
您可以使用以下查询,它会给出您需要的结果..
select t1.recID,t1.Version,t1.Patch,t2.cnt,
case when exists(select * from #tmp where t1.recID > #tmp.recID and t1.Patch=#tmp.Patch and t1.Version=#tmp.Version ) then 0 else t2.cnt end as cnt2
from #tmp t1 inner join (
select Version,Patch ,COUNT(recId) as cnt from #tmp
group by Version,Patch)t2
on t1.Patch=t2.Patch and t1.Version=t2.Version