我有表LessonHour
,列爲空Number
。如何填寫基於其他兩列的列
TABLE [dbo].[LessonHour]
(
[Id] [uniqueidentifier] NOT NULL,
[StartTime] [time](7) NOT NULL,
[EndTime] [time](7) NOT NULL,
[SchoolId] [uniqueidentifier] NOT NULL,
[Number] [int] NULL
)
我怎樣才能填補了Number
表每個LessonHour
所以會課時間的數量,以便? LessonHours
不能相互交叉。每所學校都制定了自己的課時模式。
示例設置數據 http://pastebin.com/efWCtUbv
什麼了我做的:
- 訂購SchoolId和開始時間
- 使用光標插入到行下一個數字,從1每次啓動
SchoolId
變化。
編輯:
解決方案與光標
select -- top 20
LH.[Id],
[StartTime],
[EndTime],
[SchoolId]
into #LH
from
LessonHour as LH
join RowStatus as RS on LH.RowStatusId = RS.Id
where
RS.IsActive = 1
select * from #LH order by SchoolId, StartTime
declare @id uniqueidentifier, @st time(7), @et time(7), @sid uniqueidentifier
declare @prev_sid uniqueidentifier = NEWID()
declare @i int = 1
declare cur scroll cursor for
select * from #LH order by SchoolId, StartTime
open cur;
fetch next from cur into @id, @st, @et, @sid
while @@FETCH_STATUS = 0
begin
--print @prev_sid
if @sid <> @prev_sid
begin
set @i = 1
end
update LessonHour set Number = @i where Id = @id
print @i
set @i = @i + 1
set @prev_sid = @sid
fetch next from cur into @id, @st, @et, @sid
end;
close cur;
deallocate cur;
drop table #LH
這是我的結果後http://pastebin.com/iZ8cnA6w
你有一個問題,你有一個想法如何解決這個問題。但你的問題是什麼?您是否實施並測試了您的解決方案?你是否遇到過任何問題,或者你想知道是否有更好的方法來做到這一點? –
非常不清楚,但讓我們試着用'ROW_NUMBER()'** [demo ....҉](https://data.stackexchange.com/stackoverflow/query/422677)** – lad2025
@WernerHenze我在找更好的解決方案。我不喜歡使用光標,但我不知道如何以任何其他方式做到這一點。 – pizycki