我遇到了间隙和孤岛解决方案的奇怪行为。有 3 列(第 3 列是非整数),结果确实是随机的。假设我们有以下查询:
Declare @Table1 TABLE
(
ID varchar(50),
yr float,
CO1 varchar(50)
);
INSERT INTO @Table1 (ID, yr, CO1)
VALUES ('I2','2011','ABE'), ('I2','2012','ABE'), ('I2','2013','ABE'),
('I2','2014','ABE'), ('I2','2014','ABE'), ('I2','2005','ABD'),
('I2','2006','ABD'), ('I2','2007','ABD'), ('I2','2008','ABD'),
('I2','2007','ABA CD'), ('I2','2011','ABA CD'), ('I2','2013','ABA CD');
SELECT
ID, CO1, StartSeqNo = MIN(yr), EndSeqNo = MAX(yr)
FROM
(SELECT
ID, yr, CO1,
rn = yr - ROW_NUMBER() OVER (PARTITION BY ID ORDER BY yr)
FROM
@Table1) a
GROUP BY
ID, CO1, rn ;
我的目标是:
ID CO1 StartSeqNo EndSeqNo
----------------------------
I2 ABA CD 2007 2007
I2 ABA CD 2011 2011
I2 ABA CD 2013 2013
I2 ABD 2005 2008
I2 ABE 2011 2014
我已经查看了 stackoverflow 和其他地方,以确定我是否遗漏了一些东西。我已经尝试过 distinct 和 dense_rank,都没有给出正确的结果
以下是我已经尝试过的 distinct 和 dense_rank 查询:
--- distinct
SELECT distinct ID,CO1, StartSeqNo=MIN(yr), EndSeqNo=MAX(yr)
FROM (
SELECT distinct ID, yr, CO1
,rn=yr-ROW_NUMBER() OVER (PARTITION BY ID ORDER BY yr)
FROM @Table1) a
GROUP BY ID, CO1, rn ;
--- with dense_rank
SELECT ID,CO1, StartSeqNo=MIN(yr), EndSeqNo=MAX(yr)
FROM (
SELECT ID, yr, CO1
,rn=yr-dense_rank() OVER (PARTITION BY ID ORDER BY yr)
FROM @Table1) a
GROUP BY ID, CO1, rn ;
我不明白为什么间隙和孤岛查询不适用于非整数列。我认为在某处分组存在问题。请帮我解决一下这个。
辛