首页 > 数据库技术 > 详细

在论坛中出现的比较难的sql问题:4(row_number函数+子查询 分组连续编号问题)

时间:2019-12-11 01:08:56      阅读:185      评论:0      收藏:0      [点我收藏+]
原文:在论坛中出现的比较难的sql问题:4(row_number函数+子查询 分组连续编号问题)

所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。


求一查询语句 

 http://bbs.csdn.net/topics/390633004

CREATE #temp (cName CHAR(1),re int)
INSERT #temp
SELECT ‘A‘,1 UNION ALL
SELECT ‘A‘,2 UNION ALL
SELECT ‘B‘,3 UNION ALL
SELECT ‘A‘,4 UNION ALL
SELECT ‘A‘,5

如何查询得到如下的结果:
cName,re,xh
-------------------
‘A‘,1,1
‘A‘,2,1
‘B‘,3,2
‘A‘,4,3
‘A‘,5,3

 

下面是我的解答:

  1. select *,
  2. dense_rank() over(order by case when exists(select t2.re from #temp t2
  3. where t1.cname = t2.cname
  4. and t1.re= t2.re + 1)
  5. then (select t2.re from #temp t2
  6. where t1.cname = t2.cname
  7. and t1.re= t2.re + 1)
  8. else t1.re
  9. end
  10. ) as xh
  11. from #temp t1
  12. /*
  13. cName re xh
  14. A 1 1
  15. A 2 1
  16. B 3 2
  17. A 4 3
  18. A 5 3
  19. */


但是这个解答是有问题的,因为当连续的记录超过3条时,就会有问题,

所以修改了一下,这个是正确的解法:

  1. create table #temp (cName CHAR(1),re int)
  2. insert into #temp
  3. SELECT ‘A‘,1 UNION ALL
  4. SELECT ‘A‘,2 UNION ALL
  5. SELECT ‘B‘,3 UNION ALL
  6. SELECT ‘A‘,4 UNION ALL
  7. SELECT ‘A‘,5 union all
  8. SELECT ‘A‘,6 union all
  9. SELECT ‘A‘,7 union all
  10. SELECT ‘D‘,8 union all
  11. SELECT ‘D‘,9 union all
  12. SELECT ‘D‘,10 union all
  13. select ‘B‘,11 union all
  14. select ‘A‘,12
  15. ;with t
  16. as
  17. (
  18. select *,
  19. row_number() over(partition by cname order by re) as rownum
  20. from #temp
  21. )
  22. select cname,
  23. re,
  24. dense_rank() over(order by case when exists(select min(t2.re) from t t2
  25. where t1.cname = t2.cname
  26. and t1.re-t1.rownum= t2.re-t2.rownum)
  27. then (select min(t2.re) from t t2
  28. where t1.cname = t2.cname
  29. and t1.re-t1.rownum= t2.re-t2.rownum)
  30. else t1.re
  31. end
  32. ) as xh
  33. from t t1
  34. /*cname re xh
  35. A 1 1
  36. A 2 1
  37. B 3 2
  38. A 4 3
  39. A 5 3
  40. A 6 3
  41. A 7 3
  42. D 8 4
  43. D 9 4
  44. D 10 4
  45. B 11 5
  46. A 12 6
  47. */


在论坛中出现的比较难的sql问题:4(row_number函数+子查询 分组连续编号问题)

原文:https://www.cnblogs.com/lonelyxmas/p/12019979.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!