2016-05-11 74 views
0

當Dense_Rank()值增加時,我想重新啓動SELECT語句中Row_Number()列的編號。我試圖用光標來做,但我面臨着一個數據四捨五入的問題。有沒有其他方式可以不使用遊標呢?當Dense_Rank()值增加時重置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 

任何想法爲什麼會發生這種舍入?提前致謝!

+1

我很困惑。你的問題是什麼 ?它是在row_number還是四捨五入? – Squirrel

回答

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; 
+0

上面的答案正是我一直在尋找的。聲明工作正常,它不會整理數據。 –