http://community.csdn.net/Expert/topic/4866/4866760.xml?temp=.2526209Create Table table1
([user]Varchar(10),
  date DateTime,
  mflage Bit,
 [count]Int)
Insert table1 Select 'a',     '2004-06-01',    0,      20
Union All Select 'b',     '2004-06-11',    0,      12
Union All Select 'b',     '2004-06-11',    1,      12
Union All Select 'a',     '2004-07-01',    0,      13
Union All Select 'a',     '2004-08-01',    0,      17
Union All Select 'a',     '2004-08-01',    1,      13
Union All Select 'b',     '2004-08-01',    1,      1
GO
Declare @S Varchar(8000)
Set @S=''
Select @S=@S+',SUM(Case When Left([date],7)='''+[date]+''' And  mflage=0 Then [count] Else 0 End) As '''+[date]+'A'' ,SUM(Case When Left([date],7)='''+[date]+''' And  mflage=1 Then [count] Else 0 End)  As '''+[date]+'B'''
From (Select Distinct Convert(Varchar(7),[date],120) As [date]  From table1) A Order By [date]
Select @S='Select [user]'+@S+' From table1 Group By [user]'
EXEC(@S)
GO
Drop Table table1
--Result
/*
user2004-06A2004-06B2004-07A2004-07B2004-08A2004-08B
a2001301713
b12120001
*/下面这个部分看不明白!!!望详解!!!呵呵!!!
Select @S=@S+',SUM(Case When Left([date],7)='''+[date]+''' And  mflage=0 Then [count] Else 0 End) As '''+[date]+'A'' ,SUM(Case When Left([date],7)='''+[date]+''' And  mflage=1 Then [count] Else 0 End)  As '''+[date]+'B'''

解决方案 »

  1.   

    SQL的动态执行...你需要参考一下动态相关的资料。
      

  2.   

    看来鱼潜水了这个语句是凑sql语句的,凑出,SUM(Case When Left([date],7)='2006-01' And  mflage=0 Then [count] Else 0 End) As '2006-01A' ,SUM(Case When Left([date],7)='2006-01' And  mflage=1 Then [count] Else 0 End)  As '2006-01B'
    ,SUM(Case When Left([date],7)='2006-02' And  mflage=0 Then [count] Else 0 End) As '2006-02A' ,SUM(Case When Left([date],7)='2006-02' And  mflage=1 Then [count] Else 0 End)  As '2006-02B'
    ...
      

  3.   

    From (Select Distinct Convert(Varchar(7),[date],120) As [date]  From table1) A Order By [date]
    呵呵 这句 又是什么意思???