我在 SQL Server 中使用计数命令时遇到问题。
我的行是
ItemCode ItemName
1 A
2 B
2 B
2 B
1 A
1 A
2 B
我需要这样的结果
Count ItemCode ItemName
1 1 A
3 2 B
2 1 A
1 2 B
我怎样才能得到这个结果?
最佳答案
这是一个间隙和孤岛类型的问题,可以使用如下的 row_number 解决方案来解决
参见 working demo
; with indexedtable as
(
select *, r=row_number() over ( order by(select null)) from t
),
rownumbers as
(
select *, r1= row_number() over (partition by ItemCode order by r) from indexedtable
)
select count=count(r-r1),ItemCode,ItemName
from rownumbers
group by ItemCode ,ItemName, r-r1
关于sql - 如何在 SQL Server 中使用 group count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51074528/