计算行sql server

时间:2016-06-19 10:28:40

标签: sql sql-server stored-procedures

我计算行数有问题。这是我的程序:

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

结果:

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

我想计算具有相同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

有什么建议吗? (对不起,英文)

1 个答案:

答案 0 :(得分:2)

您需要应用 RowNumber 窗口功能,如下所示

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

在上面的代码中,你得到的每个id都不是确定性的,如果你想要特定的id列有相同的countt,你需要按照

这样的唯一值排序
 row_number() over(partition by id order by lat) as countt