当另一列改变时,将列增加一列

时间:2016-02-02 10:49:14

标签: sql-server

早上好,我希望你很好。

我正在尝试运行一个select语句,每当其他列的值发生变化时,列会增加1,如下所示:

-------------------------------------------
|time                   |routeName|RouteID|
-------------------------------------------
|2015-12-01 00:54:01.000|routeA   |1      |
|2015-12-01 00:54:38.000|routeA   |1      |
|2015-12-01 00:56:18.000|routeA   |1      |
|2015-12-01 00:57:13.000|routeB   |2      |
|2015-12-01 00:57:43.000|routeB   |2      |
|2015-12-01 00:58:18.000|routeC   |3      |
|2015-12-01 00:59:06.000|routeA   |4      |
-------------------------------------------   

非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

试试这个,

desc

答案 1 :(得分:0)

DECLARE @table TABLE
(
    id int,
    routeName VARCHAR(10)
) 

 insert into @table values 
(1,'routeA'),  
(2,'routeA'),  
(3,'routeA'),  
(4,'routeB'),  
(5,'routeB'),  
(6,'routeC'),  
(7,'routeA')

SELECT
    t.id,
    t.routename,
    SUM(flag) OVER(ORDER BY t.id)
FROM
(
    SELECT
        a.id,
        a.routeName,
        IIF(a.routeName = b.routeName, 0, 1) as flag
    FROM @table as a
    LEFT OUTER JOIN @table as b on a.id = b.id + 1
) as t