本帖最后由 Learnfromeverthings 于 2011-01-21 13:07:57 编辑

解决方案 »

  1.   

    SELECT 
    SUM(CASE WHEN date = '2010-01-01' THEN [state] ELSE 0 END),
    SUM(CASE WHEN date = '2010-01-02' THEN [state] ELSE 0 END),
    SUM(CASE WHEN date = '2010-01-03' THEN [state] ELSE 0 END)
    FROM #stuct
    GROUP BY id
      

  2.   

    create table #stuct
     (id int,
      date datetime,
      state varchar(4)
      )insert into #stuct
    select  1,'2010-1-1',1 union all
    select  1,'2010-1-2',0 union all
    select  1,'2010-1-3',1 union all
    select  2,'2010-1-1',0 union all
    select  2,'2010-1-2',0 union all
    select  2,'2010-1-3',1   
    declare @sql varchar(8000)
    select @sql = isnull(@sql+',','')+'max(case when [date]='''+convert(varchar(20),[date],120)+''' then [state] else 0 end) as ['+convert(varchar(20),[date],120)+']'
    from (
    select distinct [date] from  #stuct t
    ) r
    select @sql = '
    select id,'+@sql+' 
    from #stuct
    group by id'
    exec(@sql)
      

  3.   


    create table #stuct
    (id int,
     date datetime,
     state varchar(4)
    )insert into #stuct
    select  1,'2010-1-1',1 union all
    select  1,'2010-1-2',0 union all
    select  1,'2010-1-3',1 union all
    select  2,'2010-1-1',0 union all
    select  2,'2010-1-2',0 union all
    select  2,'2010-1-3',1
    godeclare @sql varchar(4000)
    set @sql = 'select id'
    select @sql = @sql + ',max(case convert(varchar(10),date,120) when '''
    + date +''' then state end)['+ date +']'
    from (select distinct date from (select convert(varchar(10),date,120)date from #stuct)t)e
    select @sql = @sql + ' from #stuct group by id'
    exec (@sql)drop table #stuctid          2010-01-01 2010-01-02 2010-01-03
    ----------- ---------- ---------- ----------
    1           1          0          1
    2           0          0          1(2 行受影响)
      

  4.   

    declare @sql varchar(8000)
    select @sql = isnull(@sql+',','')+'max(case when [date]='''+convert(varchar(10),[date],120)+''' then [state] else 0 end) as ['+convert(varchar(10),[date],120)+']'
    from (
    select distinct [date] from  #stuct t
    ) r
    select @sql = '
    select id,'+@sql+' 
    from #stuct
    group by id'
    exec(@sql)
      

  5.   

    再来一个:
    declare @sql nvarchar(4000)
    set @sql = N''
    select @sql = @sql + N'[' + date + N'],' from (select distinct date = convert(varchar(10), date, 121) from #stuct) a
    set @sql = N'select * from #stuct pivot (max([state]) for date in (' + stuff(@sql, len(@sql), 1, N'') + N')) b'
    exec(@sql)
      

  6.   


    为什么要用sum 对sum 不明白
      

  7.   

    呵呵,对这儿来说,用MAX最贴切,用SUM数据也不会错。^_^