日期:2014-05-17 浏览次数:20480 次
if object_id('test') is not null
drop table test
go
CREATE TABLE test(
[b1] datetime NULL,
[b2] [nvarchar](50) NULL,
[b3] int NULL
)
go
insert into test
select '2013-6-1','AAA',1500 union all
select '2013-6-1','BBB',5000 union all
select '2013-6-2','AAA',7500 union all
select '2013-6-3','AAA',3500
go
DECLARE @s NVARCHAR(4000)
SET @s = ''
SELECT @s = @s + ',' + QUOTENAME(convert(nvarchar(100),b1,23)) + '=max(case when b1='
+ QUOTENAME(b1, '''') + ' then b3 else 0 end)'
FROM test
GROUP BY b1
EXEC('select b2'+@s+' from test group by b2')
if exists (select 1 from sys.tables where name='abc')
drop table abc
go
declare @a table(
日期 varchar(100),商品名称 varchar(10),购买数量 int)
insert into @a
select '2013-6-1','AAA',1500 union all
select '2013-6-1','BBB',5000 union all
select '2013-6-2','AAA',7500 union all
select '2013-6-3','AAA',3500 union all
select '2013-6-4','BBB',1500 union all
select '2013-6-4','AAA',6300
select * into abc from @a
declare @sql varchar(max);
select @sql=isnull(@sql,'')+',sum(case when convert(varchar,convert(datetime,日期),23)='''+日期+'''then 购买数量
else 0 end)as '''+日期+''''
from (select 日期=convert(varchar,dateadd(day,number,'2013-6-1'),23) from master..spt_values w