SQL:将顺序数据折叠到一行

我正在尝试将顺序数据折叠到一个组中.例如:在City1下面,数据应该显示2行.

请帮忙.

 CREATE TABLE #temp
    (id INT NOT NULL IDENTITY(1, 1) ,
    location1 VARCHAR(50)
    )


INSERT INTO #temp VALUES ('City1')
INSERT INTO #temp VALUES ('City2')
INSERT INTO #temp VALUES ('City1')
INSERT INTO #temp VALUES ('City1')
INSERT INTO #temp VALUES ('City2')
INSERT INTO #temp VALUES ('City2')

SELECT * FROM #temp

预期产出:

City1  1
city2  2
city1  3
city2   4 

最佳答案 请这样使用. (假设您使用的是SQL 2012)

解决方案1

select location1, x1 from 
(
    select * , ROW_NUMBER() OVER (PARTITION BY x1 order by Id) rnk from 
    (
        select * ,sum(p) over(order by id)+1 x1 from 
        (
            select * , case when location1 =  ISNULL(lag(location1) over (order by id),location1) then 0 else 1 end p   
            from temp2 
        )x
    )k
)p where rnk  = 1    

OUTPUT

location1            x1
-------------------- -----------
City1                1
City2                2
City1                3
City2                4

(4 rows affected)
点赞