SQL每日一题(20211221)
SQL每日一题(20220516)
/*
我的思路:
1.首先得出是否是连续的 用row_number根据L分组之后 再用x-rownumber
2.根据分组 去判断min(x)=max(x) 如果相等则为同一个 不相等则把他们用concat拼接起来
*/
select l,case when min(x)=max(x) then min(x) else concat(min(x),'-',max(x)) end as R from (
select *, x - row_number() over (partition by L ) as sn
from t1102
) a
group by sn,l
/*
这种就比较难,但是主要还是一种不同的实现逻辑
1.按到根据x排序后 的row_number 然后去left join 让他去跟前一个序号进行比较 序号=序号+1 这样得到的就是他的下一个序号
2.然后判断l如果不相等 或者l是空的话就说明找到了 不是连续的下一个开头的x
3.在用row_number 根据x进行排序 如果是1的话就直接concat与x2 如果不是1的话用Lag函数取取他的上一个值进行concat连接
*/
select c.x,
c.l,
case
when row_number() over (order by c.x) = 1
then concat(row_number() over (order by x), '-', x2)
else concat(lag(x2 + 1) over (order by x2), '-', x2) end as r
from (select a.x,
a.l,
case when a.l <> b.l or b.l is null then a.x else null end as x2
from (select x,
l,
row_number() over (order by x) 序号
from T1102) a
left join (select x,
l,
row_number() over (order by x) 序号
from T1102) b
on b.序号 = a.序号 + 1
where case when a.l <> b.l or b.l is null then a.x else null end is not null) c
order by c.l
SELECT T3.L,T3.X,LEAD(T3.X, 1, T3.X + 2) OVER (ORDER BY T3.X) - 1 a ,
T3.X || '-' || (LEAD(T3.X, 1, T3.X + 2) OVER (ORDER BY T3.X) - 1) AS R
FROM (SELECT T1.*, NVL(T2.X, 0) X1
FROM T0114 T1
LEFT JOIN T0114 T2 ON T1.X = T2.X + 1 AND T1.L = T2.L
WHERE NVL(T2.X, 0) = 0) T3