如何根据另外两列填充列

时间:2016-01-12 16:52:33

标签: tsql

我的表格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

我该怎么做:

  1. 按SchoolId和StartTime排序
  2. 使用光标插入行的下一个数字,每次SchoolId更改时从1开始。
  3. 编辑:

    使用光标解决方案

    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

    之后的结果

2 个答案:

答案 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返回。上面的表定义应该可以解决问题。

enter image description here