我的表temp包含4列 如
create table Temp
(
seqno int identity (1,1),
name varchar(20),
towncd numeric,
Counttown_cd,
)
我想写一个Query,它返回城镇的数量但是如果name和towncd是相同的 然后计数寿衣在之前的记录中添加 喜欢
1 man 0001
2 man 0001
3 test 0003
4 man 0001
5 man 0001
它回来了
如
1 man 0001 2
2 man 0001 null
3 test 0003 1
4 man 0001 2
5 man 0001 null
我尝试了以下查询:
SELECT p.seqno ,p.name,P.towncd ,COUNT(P.towncd )Counttown_cd
FROM temp P
GROUP BY P.name,P.towncd ,p.seqno
order by p.seqno
答案 0 :(得分:6)
您对问题的修改为原始问题添加了空白和岛屿问题。这可以通过子查询中的两个row_number()
来解决,如下所示:
select seqno, name, towncd
, Counttown_cd = case
when row_number() over (partition by name,towncd,grp order by seqno) = 1
then count(*) over (partition by name,towncd, grp)
else null
end
from (
select *
, grp = row_number() over (partition by name,towncd order by seqno)
- row_number() over (order by seqno)
from temp
) t
order by seqno
rextester演示:http://rextester.com/VGXI71945
返回:
+-------+------+--------+--------------+
| seqno | name | towncd | Counttown_cd |
+-------+------+--------+--------------+
| 1 | man | 0001 | 2 |
| 2 | man | 0001 | NULL |
| 3 | test | 0003 | 1 |
| 4 | man | 0001 | 2 |
| 5 | man | 0001 | NULL |
+-------+------+--------+--------------+
<小时/> 回答原始问题:
使用case
表达式和两个窗口函数(row_number()
和count(*) over()
)仅显示第一个name,towncd
实例的计数:
select seqno, name, towncd
, Counttown_cd = case
when row_number() over (partition by name,towncd order by seqno) = 1
then count(*) over (partition by name,towncd)
else null
end
from temp
rextester演示:http://rextester.com/NZSPR13395
返回:
+-------+------+--------+--------------+
| seqno | name | towncd | Counttown_cd |
+-------+------+--------+--------------+
| 1 | man | 0001 | 2 |
| 2 | man | 0001 | NULL |
| 3 | test | 0003 | 1 |
+-------+------+--------+--------------+