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

时间:2018-06-08 08:24:57

标签: sql sql-server

我正在尝试将顺序数据折叠到一个组中。例如:在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 

2 个答案:

答案 0 :(得分:1)

请这样使用。 (假设您使用的是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    

<强>输出

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

(4 rows affected)

答案 1 :(得分:0)

我认为获得所需内容的最直接方法是使用lag()。您似乎想要发生变化的地方:

select row_number() over (order by id) as new_id, location1
from (select t.*, lag(location1) over (order by id) as prev_location1
      from #temp t
     ) t
where prev_location1 is null or prev_location1 <> location1;

Here是一个显示解决方案的rextester。