你说的这一行呀,实际上就是要ID和日期都相同的记录合并成新的记录!上面那些只是模拟数据表的一部分!ID等于1的我列了二一的记录吗!ID等于的还可以列很多吗!

解决方案 »

  1.   

    --查询(如果 ID + [DateTime] 不会重复的话)
    select id,[DateTime]
    ,Time1=max(case gid%4 when 0 then [Time] else '' end)
    ,Time2=max(case gid%4 when 1 then [Time] else '' end)
    ,Time3=max(case gid%4 when 2 then [Time] else '' end)
    ,Time4=max(case gid%4 when 3 then [Time] else '' end)
    from(
    select id,[DateTime]=convert(char(10),[DateTime],120)
    ,[Time]=convert(char(10),[DateTime],108)
    ,gid=(select count(*) from tb where id=a.id and [DateTime]<=a.[DateTime])-1
    from tb a
    )a group by id,[DateTime],gid/4
      

  2.   

    --测试--测试数据
    create table tb(ID int,[DateTime] datetime)
    insert tb select 1,'2004-1-1 08:30:00'
    union all select 1,'2004-1-1 12:00:00'
    union all select 1,'2004-1-1 13:30:00'
    union all select 1,'2004-1-1 17:30:00'
    union all select 1,'2004-1-2 08:30:00'
    union all select 1,'2004-1-2 12:00:00'
    union all select 1,'2004-1-2 13:30:00'
    union all select 1,'2004-1-2 17:30:00'
    union all select 2,'2004-1-1 08:30:00'
    union all select 2,'2004-1-1 12:00:00'
    union all select 2,'2004-1-1 13:30:00'
    union all select 2,'2004-1-1 17:30:00'
    go--查询(如果 ID + [DateTime] 不会重复的话)
    select id,[DateTime]
    ,Time1=max(case gid%4 when 0 then [Time] else '' end)
    ,Time2=max(case gid%4 when 1 then [Time] else '' end)
    ,Time3=max(case gid%4 when 2 then [Time] else '' end)
    ,Time4=max(case gid%4 when 3 then [Time] else '' end)
    from(
    select id,[DateTime]=convert(char(10),[DateTime],120)
    ,[Time]=convert(char(10),[DateTime],108)
    ,gid=(select count(*) from tb where id=a.id and [DateTime]<=a.[DateTime])-1
    from tb a
    )a group by id,[DateTime],gid/4
    go--删除测试
    drop table tb/*--测试结果id          DateTime   Time1      Time2      Time3      Time4      
    ----------- ---------- ---------- ---------- ---------- ---------- 
    1           2004-01-01 08:30:00   12:00:00   13:30:00   17:30:00  
    1           2004-01-02 08:30:00   12:00:00   13:30:00   17:30:00  
    2           2004-01-01 08:30:00   12:00:00   13:30:00   17:30:00  (所影响的行数为 3 行)
    --*/
      

  3.   

    select ID
    ,convert(varchar(10),DateTime,102)
    ,Time1=max(case when datepart(hh,DateTime)=8 
    then convert(varchar(10),DateTime,108) else '' end)
    ,Time2=max(case when datepart(hh,DateTime)=12 
    then convert(varchar(10),DateTime,108) else '' end)
    ,Time3=max(case when datepart(hh,DateTime)=13 
    then convert(varchar(10),DateTime,108) else '' end)
    ,Time4=max(case when datepart(hh,DateTime)=17 
    then convert(varchar(10),DateTime,108) else '' end)
    from @tb
    group by ID,convert(varchar(10),DateTime,102)