当Dense_Rank()值增加时,我想重新启动SELECT语句中Row_Number()列的编号。我尝试用光标做到这一点,但我面临着舍入我的数据的问题。有没有其他方法可以不使用游标?
DECLARE @RowNum as INT;
DECLARE @DenseRank as INT;
DECLARE @DenseRankPrevious as INT;
DECLARE @RD_ROI1_minus_RD_ROI3 as NVARCHAR(MAX);
DECLARE @RD_ROI2_minus_RD_ROI3 as NVARCHAR(MAX);
DECLARE @Cursor as CURSOR;
SET @RowNum = 0;
SET @Cursor = CURSOR FOR
SELECT DENSE_RANK() OVER (ORDER BY [RD_RF_ID]) AS DenseRank, [RD_ROI1_minus_RD_ROI3]
FROM [dbo].[vw_Raw_Data] WHERE [dbo].[vw_Raw_Data].RD_GUID_ID = 433
CREATE TABLE #TempTable(
RowNum int,
DenseRank int,
ROI1_New NVARCHAR(MAX))
OPEN @Cursor;
FETCH NEXT FROM @Cursor INTO @DenseRank, @RD_ROI1_minus_RD_ROI3;
SET @DenseRankPrevious = @DenseRank;
WHILE @@FETCH_STATUS = 0
BEGIN
IF @DenseRankPrevious = @DenseRank
SET @RowNum = @RowNum + 1;
ELSE
BEGIN
SET @RowNum = 0;
SET @RowNum = @RowNum + 1;
SET @DenseRankPrevious = @DenseRank;
END
INSERT INTO #TempTable
SELECT @RowNum, @DenseRank, @RD_ROI1_minus_RD_ROI3 ;
FETCH NEXT FROM @Cursor INTO @DenseRank, @RD_ROI1_minus_RD_ROI3;
END
CLOSE @Cursor;
DEALLOCATE @Cursor;
SELECT * FROM #TempTable
DROP TABLE #TempTable
上面的代码给出了以下结果
- 1 1 178.409
- 2 1 173.23
- 3 1 164.867
- 4 1 165.52
- 5 1 153.351
- 6 1 160.773
- 7 1 157.694
而不是预期的以下内容。
- 1 1 178,409039893888
- 2 1 173,230282624222
- 3 1 164,86654423018
- 4 1 165,52035506581
- 5 1 153,351290684624
- 6 1 160,773492500765
- 7 1 157,694316906438
知道这种四舍五入的原因吗?提前谢谢!
答案 0 :(得分:0)
为什么要使用游标?
SELECT ROW_NUMBER() OVER (PARTITION BY DenseRank ORDER BY (SELECT NULL)) as rn,
rd.*
FROM (SELECT DENSE_RANK() OVER (ORDER BY rd.RD_RF_ID) AS DenseRank,
RD_ROI1_minus_RD_ROI3
FROM dbo.vw_Raw_Data rd
WHERE rd.RD_GUID_ID = 433
) rd;