当前位置: 代码迷 >> 报表 >> 求好手来解决一下
  详细解决方案

求好手来解决一下

热度:154   发布时间:2016-05-05 07:33:44.0
求高手来解决一下。
Excel报表内容,

名称     日期   产量     
A       5.25     120
A       5.26     120
A       5.27     120
B       2.25     150
B       2.26     150
B       2.27     150
C       2.25     200
把上表转换为
物品            总量        日期1          日期2           日期3   
名称            360          5.25           5.26            5.27
A               360         120             120             120
B               450          150            150             150
C               200          200             空              空


请高手帮看下~!
------解决方案--------------------
示例:
----------------------------------------------------------------
-- Author  :fredrickhu(小F,向高手学习)
-- Date    :2010-06-03 10:25:21
-- Version:
--      Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86) 
--    Nov 24 2008 13:01:59 
--    Copyright (c) 1988-2005 Microsoft Corporation
--    Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go 
create table [tb]([SationID] int,[CurrentTime] datetime,[要素1] int,[要素2] int)
insert [tb]
select 1,'2008-1-2 1:00:00',111,112 union all
select 1,'2008-1-2 2:00:00',121,122 union all
select 2,'2008-1-2 1:00:00',211,212 union all
select 2,'2008-1-2 2:00:00',221,222
--------------开始查询--------------------------
declare @sql varchar(8000)
set @sql = 'select SationID,要素 '
select @sql = @sql + ' , max(case when ltrim(datepart(hh,CurrentTime))=''' + ltrim(datepart(hh,CurrentTime)) + ''' then value else null end) [' + ltrim(datepart(hh,CurrentTime)) + ']'
from (select distinct SationID,CurrentTime,'要素1' 要素,要素1 value from tb union all 
select SationID,CurrentTime,'要素2',要素2 from tb ) as a
set @sql = @sql + ' from (select SationID,CurrentTime,''要素1'' as  要素,要素1 value from tb union all 
select SationID,CurrentTime,''要素2'',要素2 from tb )t group by SationID,要素'
exec(@sql) 
----------------结果----------------------------
/* SationID    要素    1           2           1           2           1           2           1           2
----------- ----- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
1           要素1   111         121         111         121         111         121         111         121
2           要素1   211         221         211         221         211         221         211         221
  相关解决方案