SQL查询连续号码段的巧妙解法
在ITPUB上有一则非常巧妙的SQL技巧,学习一下,记录在这里。
最初的问题是这样的:
我有一个表结构,
fphm,kshm
2014,00000001
2014,00000002
2014,00000003
2014,00000004
2014,00000005
2014,00000007
2014,00000008
2014,00000009
2013,00000120
2013,00000121
2013,00000122
2013,00000124
2013,00000125
(第二个字段内可能是连续的数据,可能存在断点。)
怎样能查询出来这样的结果,查询出连续的记录来。
就像下面的这样?
2014,00000001,00000005
2014,00000009,00000007
2013,00000120,00000122
2013,00000124,00000125
ITPUB上的朋友给出了一个非常巧妙的答案:
SELECT b.fphm, MIN (b.kshm) Start_HM, MAX (b.kshm) End_HM
FROM (SELECT a.*, TO_NUMBER (a.kshm - ROWNUM) cc
FROM (SELECT *
FROM t
ORDER BY fphm, kshm) a
) b
GROUP BY b.fphm, b.cc
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn