SQL Server 2012 First_Value函数

时间:2018-01-25 17:04:14

标签: sql sql-server

我被困2个案件,我需要你的协助。 表格如下:

Sample Table

SR UID旗帜费用
1 AAA 1 100.00
2 AAA 0 0.00
3 AAA 0 0.00
4 AAA 1 120.00
5 AAA 0 0.00
6 AAA 0 0.00
7 AAA 1 140.00
1 BBB 1 200.00
2 BBB 0 0.00
3 BBB 0 0.00
4 BBB 0 0.00
5 BBB 0 0.00
6 BBB 0 0.00
7 BBB 1 400.00

如何使用First_value函数将费用列中的0.00值替换为第一个值,其中Flag = 1分区UID

结果应如下所示 Results

SR UID标志费First_Value
1 AAA 1 100.00 100.00
2 AAA 0 0.00 100.00
3 AAA 0 0.00 100.00
4 AAA 1 120.00 120.00
5 AAA 0 0.00 120.00
6 AAA 0 0.00 120.00
7 AAA 1 140.00 140.00
1 BBB 1 200.00 200.00
2 BBB 0 0.00 200.00
3 BBB 0 0.00 200.00
4 BBB 0 0.00 200.00
5 BBB 0 0.00 200.00
6 BBB 0 0.00 200.00
7 BBB 1 400.00 400.00

1 个答案:

答案 0 :(得分:0)

有一个想法,就像Op一样使用FIRST_VALUE试图:

CREATE TABLE #Sample (SR int, UID char(3), Flag bit, Fees decimal(5,2));
INSERT INTO #Sample
VALUES
    (1,'AAA',1,100.00),
    (2,'AAA',0,0.00  ),
    (3,'AAA',0,0.00  ),
    (4,'AAA',1,120.00),
    (5,'AAA',0,0.00  ),
    (6,'AAA',0,0.00  ),
    (7,'AAA',1,140.00),
    (1,'BBB',1,200.00),
    (2,'BBB',0,0.00  ),
    (3,'BBB',0,0.00  ),
    (4,'BBB',0,0.00  ),
    (5,'BBB',0,0.00  ),
    (6,'BBB',0,0.00  ),
    (7,'BBB',1,400.00);

WITH Groups AS(
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY UID ORDER BY SR) - 
           ROW_NUMBER() OVER (PARTITION BY UID, Flag ORDER BY SR) AS Grp
    FROM #Sample)
SELECT SR, UID, Flag, Fees,
       FIRST_VALUE(Fees) OVER (PARTITION BY UID, CASE Grp WHEN 0 THEN 1 ELSE Grp END ORDER BY SR)
FROM Groups
ORDER BY UID, SR;

DROP TABLE #Sample