[英]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.我有一个 SQL 问题,我无法仅使用 SQL 来解决。
Question is: I have a table with 2 columns.问题是:我有一个有 2 列的表。 One is
Question
(int column), other one is Answer
( varchar(1)
) like this:一个是
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
Output should look like this; Output 应该是这样的;
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..抱歉,我对 SQL 真的很陌生,所以我不知道如何编写此查询..
This is a gaps-and-islands problem.这是一个差距和孤岛问题。 You can handle it by using
row_number()
to enumerate the values for the answers.您可以使用
row_number()
枚举答案的值来处理它。 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.这种方法的好处是,即使
question
的数字有差距,它也能工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.