我的表格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开始。编辑:
使用光标解决方案
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
之后的结果
答案 0 :(得分:1)
合并StackOverflow问题中的信息SQL Update with row_number()和 How do I use ROW_NUMBER()?:
with cte as (
select number, ROW_NUMBER() OVER(partition by schoolid order by starttime asc) as r from lessonhour
)
update cte
set number = r
答案 1 :(得分:-1)
这会有效吗
CREATE TABLE [dbo].[LessonHour]
(
[Id] [uniqueidentifier] NOT NULL,
[StartTime] [time](7) NOT NULL,
[EndTime] [time](7) NOT NULL,
[SchoolId] [uniqueidentifier] NOT NULL,
[Number] AS DATEDIFF(hour,[StartTime],[EndTime])
)
因此,如果我正确理解了这个问题,您需要一个计算列,该列接收[StartTime]和[EndTime]的值,并将该课程的小时数作为int返回。上面的表定义应该可以解决问题。