数据表
姓名 日期    考勤时间
a 2012-7-26   08:00:00
a 2012-7-26    12:01:03
b 2012-7-12   06:02:04


在程序中显示
姓名 日期   时间1     时间2        时间3  时间4
a 2012-7-26  08:00:00   12:01:03
b 2012-7-12   06:02:04 请问这个SQL代码要怎么写?

解决方案 »

  1.   


    if object_id('tempdb..#t') is not null
    drop table #t
    select * into #t from(
    select 'a' as 姓名,'2012-7-26' as 日期,'08:00:00' as 考勤时间 union all
    select 'a','2012-7-26','12:01:03' union all
    select 'b','2012-7-12','06:02:04')tb;with cte as(
    select *,rid=row_number()over(partition by 姓名,日期 order by 考勤时间) from #t
    )
    select 姓名,日期,
    max(case when rid=1 then 考勤时间 else null end) as 时间1,
    max(case when rid=2 then 考勤时间 else null end) as 时间2,
    max(case when rid=3 then 考勤时间 else null end) as 时间3,
    max(case when rid=4 then 考勤时间 else null end) as 时间4
    from cte group by 姓名,日期
      

  2.   

    如果我有2000个人,是否全部都要union all一下啊?
      

  3.   

    ifobject_id('tb')isnotnulldroptabletbgocreatetabletb(姓名varchar(10),课程varchar(10),分数int)insertintotbvalues('张三','语文',74)insertintotbvalues('张三','数学',83)insertintotbvalues('张三','物理',93)insertintotbvalues('李四','语文',74)insertintotbvalues('李四','数学',84)insertintotbvalues('李四','物理',94)goselect*fromtbgo姓名       课程       分数---------- ---------- -----------张三       语文        74张三       数学        83张三       物理        93李四       语文        74李四       数学        84李四       物理        94
    --变量按sql语言顺序赋值declare@sqlvarchar(500)set@sql='select姓名'select@sql=@sql+',max(case课程when '''+课程+''' then分数else 0 end)['+课程+']'from(selectdistinct课程fromtb)a--同from tb group by课程,默认按课程名排序set@sql=@sql+' from tb group by姓名'exec(@sql) --使用isnull(),变量先确定动态部分declare@sqlvarchar(8000)select@sql=isnull(@sql+',','')+' max(case课程when '''+课程+''' then分数else 0 end) ['+课程+']'from(selectdistinct课程fromtb)asa      set@sql='select姓名,'+@sql+' from tb group by姓名'exec(@sql)
      

  4.   


    IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = '数据表')
    BEGIN
    DROP TABLE 数据表
    END
    GO
    CREATE TABLE 数据表
    (
    姓名 VARCHAR(10),
    日期 VARCHAR(10),
    考勤时间 VARCHAR(10)
    )
    GO
    INSERT INTO 数据表
    SELECT 'a', '2012-7-26','08:00:00' UNION
    SELECT 'a', '2012-7-26','12:01:03' UNION
    SELECT 'b', '2012-7-12','06:02:04'
    GOdeclare @sql varchar(max)
    select @sql=isnull(@sql+',','')
      +'max(case when rn='+ltrim(rn)+' then 考勤时间 end) as 考勤时间' + RTRIM(rn)
    from
    (select distinct rn=row_number() over(partition by 姓名,日期 order by 考勤时间) from 数据表) tEXEC ('select 姓名,日期,'
      +@sql
      +' from (select *,rn=row_number() over(partition by 姓名,日期 order by 考勤时间) from 数据表) t group by 姓名,日期 ORDER BY 姓名,日期'
      )姓名 日期 考勤时间1 考勤时间2
    a 2012-7-26 08:00:00 12:01:03
    b 2012-7-12 06:02:04 NULL
      

  5.   

    如果是在VB中的话,这SQL语句要怎么写?