修改了下,请看 CREATE TABLE [dbo].[P] ( [M01] [char] (10) COLLATE Chinese_PRC_BIN NULL , [M02] [varchar] (10) COLLATE Chinese_PRC_BIN NOT NULL , [M03] [char] (10) COLLATE Chinese_PRC_BIN NULL ) ON [PRIMARY] GO INSERT INTO P VALUES ('BM','2010/01/12','本') declare @s varchar(8000) select @s = isnull(@s+',','')+'''['+M02+']''=max(case when M02 = '''+M02+''' then M03 else ''DF'' end)' from (select distinct M02 from P) a exec('select M01,'+ @s+' from P GROUP BY M01')DROP TABLE P
M01 [2010/01/12] ---------- ------------ BM 本
declare @s varchar(8000) select @s = isnull(@s+',','')+'[['+M02+']]]=max(case when M02 = '''+M02+''' then M03 else ''DF'' end)' from (select distinct M02 from P) aexec('select M01,'+ @s+' from P GROUP BY M01')/* M01 [2010/01/12] ---------- ------------ BM 本 */
CREATE TABLE [dbo].[P] (
[M01] [char] (10) COLLATE Chinese_PRC_BIN NULL ,
[M02] [varchar] (10) COLLATE Chinese_PRC_BIN NOT NULL ,
[M03] [char] (10) COLLATE Chinese_PRC_BIN NULL
) ON [PRIMARY]
GO
INSERT INTO P VALUES ('BM','2010/01/12','本') declare @s varchar(8000)
select @s = isnull(@s+',','')+'''['+M02+']''=max(case when M02 = '''+M02+''' then M03 else ''DF'' end)'
from (select distinct M02 from P) a exec('select M01,'+ @s+' from P GROUP BY M01')DROP TABLE P
---------- ------------
BM 本
select @s = isnull(@s+',','')+'[['+M02+']]]=max(case when M02 = '''+M02+''' then M03 else ''DF'' end)'
from (select distinct M02 from P) aexec('select M01,'+ @s+' from P GROUP BY M01')/*
M01 [2010/01/12]
---------- ------------
BM 本
*/
/*
[a]
-----------
1
*/