SQL数据表按天横向分类汇总?
表名:MO_TABLE
编号 名称 产量 完成日期
A01 车间A 900 2013-06-10
A02 车间B 700 2013-06-10
A01 车间A 600 2013-06-11
A02 车间B 1300 2013-06-11
A01 车间A 800 2013-06-12
A02 车间B 600 2013-06-12
.........
编号 名称 2013-06-10 2013-06-11 2013-06-12 ..........
A01 车间A 900 600 800
A02 车间B 700 1300 600
按天横向分类汇总
[解决办法]
if object_id('[MO_TABLE]') is not null drop table [MO_TABLE]
go
create table [MO_TABLE] (编号 nvarchar(6),名称 nvarchar(6),产量 int,完成日期 datetime)
insert into [MO_TABLE]
select 'A01','车间A',900,'2013-06-10' union all
select 'A02','车间B',700,'2013-06-10' union all
select 'A01','车间A',600,'2013-06-11' union all
select 'A02','车间B',1300,'2013-06-11' union all
select 'A01','车间A',800,'2013-06-12' union all
select 'A02','车间B',600,'2013-06-12'
select * from [MO_TABLE]
declare @sql varchar(8000)
select @sql = isnull(@sql + '],[' , '') + CONVERT(VARCHAR(10),完成日期,120) from [MO_TABLE] group by CONVERT(VARCHAR(10),完成日期,120)
set @sql = '[' + @sql + ']'
exec ('select * from (select * from [MO_TABLE]) a pivot (max(产量) for 完成日期 in (' + @sql + ')) b')
/*
编号名称2013-06-102013-06-112013-06-12
A01车间A900600800
A02车间B7001300600*/