简体   繁体   中英

How can compare if two consecutive rows are arbitrary in SQL Server?

I have a SQL question, I'm not able to solve only using SQL.

Question is: I have a table with 2 columns. One is Question (int column), other one is Answer ( varchar(1) ) like this:

Question  Answer
--------+---------
1       |   A
2       |   A
3       |   C
4       |   D
5       |   D
6       |   D
7       |   E
8       |   A
9       |   B
10      |   A
11      |   A
12      |   A

Output should look like this;

Range        Answer
-----------+----------
1-2        |   A
3-3        |   C
4-6        |   D
7-7        |   E
8-8        |   A
9-9        |   B
10-12      |   A

I was just able to do this,

select question, answer
from table
order by answer, question asc

Sorry, I'm really new to SQL, so I don't know how to write this query..

This is a gaps-and-islands problem. You can handle it by using row_number() to enumerate the values for the answers. The difference between this and the question is constant -- identifying the islands:

select min(question), max(question), answer
from (select t.*, row_number() over (partition by answer order by question) as seqnum
      from t
     ) t
group by (question - seqnum), answer
order by min(question);

This is a gaps-and-islands problem. Here is an approach using the difference between row numbers to define the groups.

select 
    concat(min(question), '-', max(question)) range,
    answer 
from (
    select 
        t.*,
        row_number() over(order by question) rn1,
        row_number() over(partition by answer order by question) rn2
    from mytable t
) t
group by answer, rn1 - rn2
order by min(question)

The upside of this approach is that it works even if question s numbers have gaps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM