我有一張t_times看起來像這樣的桌子
| 開始時間 | 時間結束 | Number_of_slots | Slot_Duration |
|---|---|---|---|
| 08:00 | 09:00 | 6 | 10 |
| 09:00 | 09:30 | 1 | 30 |
我需要使用要創建的值創建一個t_times表t_slots
| 開始時間 | 時間結束 | 期間 |
|---|---|---|
| 08:00 | 08:10 | 10 |
| 08:10 | 08:20 | 10 |
| 08:20 | 08:30 | 10 |
| 08:30 | 08:40 | 10 |
| 08:40 | 08:50 | 10 |
| 08:50 | 09:00 | 10 |
| 09:00 | 09:30 | 30 |
本質上,對于 number_of_slots 欄位中指定的每個值,我需要:
- 在目標表中創建新行
- 考慮到 slot_duration 欄位的值,使用持續時間添加相應的時隙(開始和結束)。即對于 6 的值,我需要添加 6 行,每行增量為 10 分鐘,每行使用 start_time 作為起始值
我可以用游標來做,但這似乎是一種非常迂回的方式。有人可以指出我的 SQL 方向嗎?謝謝!!!
uj5u.com熱心網友回復:
所以這里的主要思想是使用帶有數字表的經典方法。將這樣的表作為持久表是很常見的,因此不需要在運行時生成它。它是分析東西的常用工具,就像你的一樣。第二個是將它與正確謂詞上的源連接。
use tempdb
go
drop table if exists src
go
create table src (
start_time time
,End_time time
,Number_of_slots int
,Slot_Duration int
)
go
insert into src values
('08:00', '09:00', 6, 10)
,('09:00', '09:30', 1, 30)
go
;with nums as (
select row_number() over(order by (select null)) as n
from sys.all_columns
)
select start_time, dateadd(MINUTE, n*Slot_Duration, start_time) as end_time
, Slot_Duration as Duration
from src
join nums on src.Number_of_slots >= nums.n
order by start_time, end_time
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483412.html
標籤:sql服务器
上一篇:如何使用CROSSAPPLY在SQL中將多個逗號分隔的列拆分為單獨的行
下一篇:如何更改鍵盤快捷鍵-F5到Ctrl Enter在SQLServerManagementStudio中執行SQL命令
