SQL Server How to Group Similar Rows in Sql?

7gcisfzg  于 2023-03-17  发布在  其他
关注(0)|答案(3)|浏览(146)
DATEADRESS
2010-09-02ENGLAND
2010-09-03ENGLAND
2010-09-04ENGLAND
2010-09-05ENGLAND
2010-09-06GERMANY
2010-09-07GERMANY
2010-09-08GERMANY
2011-09-03ENGLAND
2012-09-02ENGLAND
2013-09-03ENGLAND

I have a table like this and what I want to do, I want the result I want to get, how can I do it?

DATEADRESS
2010-09-02 - 2010-09-05ENGLAND
2010-09-06 - 2010-09-08GERMANY
2011-09-03 - 2013-09-03ENGLAND
mbjcgjjk

mbjcgjjk1#

You have a gaps and islands problem here, you could use the difference between two row_numbers approach to solving it, try the following:

select concat_ws(' - ', min([date]), max([date])) as [date],
       address
from
(
  select *,
   row_number() over (order by date) -
   row_number() over (partition by address order by [date]) grp
  from table_name
) t
group by address, grp
order by min([date])

see demo

jaxagkaj

jaxagkaj2#

you can try this

SELECT CONCAT(MIN(DATE), ' - ', MAX(DATE)), ADRESS
    FROM tablename GROUP BY ADRESS
roejwanj

roejwanj3#

As already mentioned before this is a gaps and islands problem.

This is an other way to solve it :

with cte as (
  select *, lag(ADRESS, 1, ADRESS) over(order by id) as lag_ADRESS
  from ( select row_number() over() as id, t.* from mytable t) s
  ORDER BY id
),
cte2 as (
  select *, sum(case when ADRESS = lag_ADRESS then 0 else 1 end) over (order by id) as grp
  from cte
)
select ADRESS, concat(min(DATE),' - ', max(Date)) as ADRESS
from cte2
group by ADRESS, grp

Lag() is a window function that allows you to look back a number of rows and access data of that row from the current row.

Then we check by a CASE WHEN clause where the records have been broken.

Demo here

相关问题