在SQLServer中,如果两个连续的行是任意的,如何进行比较?

bweufnob  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(314)

我有一个sql问题,我不能只用sql来解决。
问题是:我有一个有两列的表。一个是 Question (int列),另一个是 Answer ( varchar(1) )像这样:

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

输出应该是这样的;

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

我只是能做到,

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

抱歉,我对sql非常陌生,所以我不知道如何编写此查询。。

qyyhg6bp

qyyhg6bp1#

这是一个缺口和孤岛问题。你可以用 row_number() 枚举答案的值。这和问题之间的区别是不变的——确定岛屿:

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);
c0vxltue

c0vxltue2#

这是一个缺口和孤岛问题。下面是一种使用行号之间的差异来定义组的方法。

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)

这种方法的好处是,即使 question s的数字有差距。

相关问题