我有一个表,其中有一个名为 ID 的整数列,其值可能有间隙(例如 1、2、3、4、7、8、10、14、15、16、20)
我想找到一个查询,在上面的示例中,结果如下:
1-4 7-8 10 14-16 20
= 更新 =
感谢下面的代码(它似乎在 SQL Server 中运行良好),我觉得我非常接近让它在 MS-Access 中运行,这是目标。尽管在我的陈述中我仍然遇到语法错误,但我无法弄清楚......
选择值从(
SELECT islands.PORTID, CSTR(islands.PORTID ) as val
FROM MYTABLE islands
WHERE NOT EXISTS (SELECT * FROM MYTABLE t2 WHERE t2.PORTID = islands.PORTID - 1)
AND NOT EXISTS (SELECT * FROM MYTABLE t2 WHERE t2.PORTID = islands.PORTID + 1)
UNION
SELECT
rngStart.PORTID
,CSTR(rngStart.PORTID ) + '-'
+ CSTR(MIN(rngEnd.PORTID)) as val
FROM MYTABLE rngStart
INNER JOIN MYTABLE checkNext ON checkNext.PORTID = rngStart.PORTID + 1
INNER JOIN
(
SELECT PORTID
FROM MYTABLE tblRangeEnd
WHERE NOT EXISTS (SELECT * FROM MYTABLE t2 WHERE t2.PORTID = tblRangeEnd.PORTID + 1)
) rngEnd on rngEnd.PORTID > rngStart.PORTID
WHERE NOT EXISTS (SELECT * FROM MYTABLE t2 WHERE t2.PORTID = rngStart.PORTID - 1)
GROUP BY rngStart.PORTID
) as tbl ORDER BY PORTID ASC