简体   繁体   English

计数SQL Server行

[英]Counting rows sql server

I have a problem with counting rows. 我在计算行数时遇到问题。 This is my procedure : 这是我的程序:

DECLARE @result table(id int,latitude float, longitude float)
Declare @z int = 1
while (@z <5) 
BEGIN
INSERT INTO
@result
SELECT 
id,
loc.STPointN(@z).Lat as lat,
loc.STPointN(@z).Long as long
FROM test6
SET @z = @z+1
END
Select * from @result
ORDER BY id

Results: 结果:

ID  lat         long
1   16,71175    52,689702
1   17,008381   52,247983
2   17,228107   52,689702
2   17,008381   42,247983
2   16,71175    42,689702

I want to count rows with same ID, somthing like : 我想计算具有相同ID的行,例如:

ID  lat         long       count
1   16,71175    52,689702  1
1   17,008381   52,247983  2
2   17,228107   52,689702  1
2   17,008381   42,247983  2
2   16,71175    42,689702  3

Any advice ? 有什么建议吗? (Sorry for english) (对不起,英语)

You need to apply RowNumber window function like below 您需要应用RowNumber窗口函数,如下所示

select
id,
lat,
long,
row_number() over(partition by id order by id) as countt
from 
yourtable

In the above code countt per id you get is not deterministic,if you want specific id column to have same countt,you need to order by unique value like 在上面获得的每个id的代码计数中不是确定性的,如果希望特定的id列具有相同的计数,则需要按唯一值进行排序,例如

 row_number() over(partition by id order by lat) as countt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM