表数据大致是这样的ID    数据         时间
1      10          2008-3-2 8:00
1      20          2009-3-2 8:00
1      30          2008-6-5 8:00
1      40          2009-6-5 8:00。。8      10          2008-3-2 8:00
8      20          2009-3-2 8:00
8      30          2008-6-5 8:00
8      40          2009-3-5 8:00现在我想建立一个视图,视图的结果是这样的
ID   年份   3月2日8时据    6月5日8时据  
1     2008     10           30
1     2009     20           40

8     2008     10           30
8     2009     20           40
 我现在的做法是分别创建单个视图去出一天的数据,在通过年份管理把多个单天的视图组合成一个最终结果的视图,但是这样做不仅视图多而且,只要有一个单天的视图没有数据,那么这个id就不会产生当年的数据。
求高速赐教

解决方案 »

  1.   

    use PracticeDB
    go
    if exists (select 1 from sysobjects where name='tb')
    drop table tb
    go
    create table tb (ID int ,数据 int,时间 datetime)
    go
    insert into tb
    select 1 ,10, '2008-3-2 8:00' union all
    select 1 ,20, '2009-3-2 8:00' union all
    select 1 ,30, '2008-6-5 8:00' union all
    select 1 ,40, '2009-6-5 8:00' union all
    select 8 ,10, '2008-3-2 8:00' union all
    select 8 ,20, '2009-3-2 8:00' union all
    select 8 ,30, '2008-6-5 8:00' union all
    select 8 ,40, '2009-6-5 8:00'
    select id,left(convert(varchar(10),时间,120),4) as[年份],sum(case right(convert(varchar,时间,120),LEN(convert(varchar,时间,120))-5) when '03-02 08:00:00' then 数据 else 0 end) as [3月2日8时据],
                                                             sum(case right(convert(varchar,时间,120),LEN(convert(varchar,时间,120))-5) when '06-05 08:00:00' then 数据 else 0 end) as [6月5日8时据]
    from tb
    group by id, left(convert(varchar(10),时间,120),4)
    order by ID
      

  2.   

    谢谢jaydom,你太厉害了,非常感谢
      

  3.   

    不用客气,其实tony 哥才厉害呢,呵呵
      

  4.   


    --这样?
    --> 测试数据: tb
    if object_id('tb') is not null drop table tb
    create table tb (ID int,数据 int,时间 datetime)
    insert into tb
    select 1,10,'2008-3-2 8:00' union all
    select 1,20,'2009-3-2 8:00' union all
    select 1,30,'2008-6-5 8:00' union all
    select 1,40,'2009-6-5 8:00' union all
    select 8,10,'2008-3-2 8:00' union all
    select 8,20,'2009-3-2 8:00' union all
    select 8,30,'2008-6-5 8:00' union all
    select 8,40,'2009-3-5 8:00'
    godeclare @sql varchar(8000)
    set @sql='select id,年份=year(时间)'
    select @sql=@sql+',['+ltrim(month(时间))+'月'+ltrim(day(时间))+'日'+ltrim(datepart(hh,时间))+'时据]=sum(case when datediff(hh,时间,'''+convert(varchar(20),时间,120)+''')=0 then 数据 else 0 end)'
    from (select distinct 时间 from tb)a
    set @sql=@sql+' from tb group by id,year(时间) order by id'
    exec(@sql)--结果:
    id          年份          3月2日8时据     6月5日8时据     3月2日8时据     3月5日8时据     6月5日8时据
    ----------- ----------- ----------- ----------- ----------- ----------- -----------
    1           2008        10          30          0           0           0
    1           2009        0           0           20          0           40
    8           2008        10          30          0           0           0
    8           2009        0           0           20          40          0