要求:撰寫一個 SQL 查詢得到 Logs 表中的連續區間的開始數字和結束數字,將查詢表按照 start_id 排序,
表:Logs的結構
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| log_id | int |
+---------------+---------+
id 是上表的主鍵,
上表的每一行包含日志表中的一個 ID,
Logs 表:
+------------+
| log_id |
+------------+
| 1 |
| 2 |
| 3 |
| 7 |
| 8 |
| 10 |
+------------+
Result Table:
+------------+--------------+
| start_id | end_id |
+------------+--------------+
| 1 | 3 |
| 7 | 8 |
| 10 | 10 |
+------------+--------------+
結果表應包含 Logs 表中的所有區間,
SQL陳述句:
select min(log_id) as start_id,max(log_id) as end_id
from(
select log_id,(log_id-row_number() over(order by log_id)) as r
from logs) a
group by r
order by log_id asc;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/287217.html
標籤:其他
下一篇:JDBC操作
