22,209
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([Id] int,[datetime] datetime,[money] int)
insert [huang]
select 1,'2013/06/01',100 union all
select 2,'2013/06/02',105 union all
select 3,'2013/06/03',106 union all
select 4,'2013/06/04',107 union all
select 5,'2013/06/05',108
--------------开始查询--------------------------
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename(CONVERT(VARCHAR(20),[datetime],101))+'=max(case when [datetime]='+quotename([datetime],'''')+' then [money] else 0 end)'
from [huang] group by [datetime]
SET @s=SUBSTRING(@s,2,LEN(@s))
EXEC('select '+@s+' from [huang] ')
----------------结果----------------------------
/*
06/01/2013 06/02/2013 06/03/2013 06/04/2013 06/05/2013
----------- ----------- ----------- ----------- -----------
100 105 106 107 108
*/