无语,看SQL.
DROP TABLE tbl
CREATE TABLE tbl
(
DQ varchar(100), -- 地区
YF int, -- 月份
CPXSE1 int, -- 产品1销售额
CPXSE2 int -- 产品2销售额
)
insert into tbl select '上海',1,100,200
insert into tbl select '上海',2,100,200
insert into tbl select '上海',3,100,200
insert into tbl select '上海',4,100,200
insert into tbl select '上海',5,100,200
insert into tbl select '上海',6,100,200
insert into tbl select '上海',7,100,200
insert into tbl select '上海',8,100,200
insert into tbl select '上海',9,100,200
insert into tbl select '上海',10,100,200
insert into tbl select '上海',11,100,200
insert into tbl select '上海',12,100,200
insert into tbl select '北京',1,100,200
insert into tbl select '北京',2,100,200
insert into tbl select '北京',3,100,200
insert into tbl select '北京',4,100,200
insert into tbl select '北京',5,100,200
insert into tbl select '北京',6,100,200
insert into tbl select '北京',7,100,200
insert into tbl select '北京',8,100,200
insert into tbl select '北京',9,100,200
insert into tbl select '北京',10,100,200
insert into tbl select '北京',11,100,200
insert into tbl select '北京',12,100,200
DECLARE @t varchar(8000)
set @t=''
select @t=@t + ' SUM(CASE WHEN YF = ' + a.YF + ' THEN CPXSE1 ELSE 0 END) [CPXSE1 ' + a.YF + ' YF], SUM(CASE WHEN YF = ' + a.YF + ' THEN CPXSE2 ELSE 0 END) [CPXSE2 ' + a.YF + ' YF],'
FROM (SELECT CAST(YF as varchar(5)) YF FROM tbl GROUP BY YF ) a
select @t='SELECT DQ, ' + LEFT(@t, LEN(@t)-1) + ' FROM tbl GROUP BY DQ'
EXEC(@t)
CREATE TABLE tbl
(
DQ varchar(100), -- 地区
YF int, -- 月份
CPXSE1 int, -- 产品1销售额
CPXSE2 int -- 产品2销售额
)
insert into tbl select '上海',1,100,200
insert into tbl select '上海',2,100,200
insert into tbl select '上海',3,100,200
insert into tbl select '上海',4,100,200
insert into tbl select '上海',5,100,200
insert into tbl select '上海',6,100,200
insert into tbl select '上海',7,100,200
insert into tbl select '上海',8,100,200
insert into tbl select '上海',9,100,200
insert into tbl select '上海',10,100,200
insert into tbl select '上海',11,100,200
insert into tbl select '上海',12,100,200
insert into tbl select '北京',1,100,200
insert into tbl select '北京',2,100,200
insert into tbl select '北京',3,100,200
insert into tbl select '北京',4,100,200
insert into tbl select '北京',5,100,200
insert into tbl select '北京',6,100,200
insert into tbl select '北京',7,100,200
insert into tbl select '北京',8,100,200
insert into tbl select '北京',9,100,200
insert into tbl select '北京',10,100,200
insert into tbl select '北京',11,100,200
insert into tbl select '北京',12,100,200
DECLARE @t varchar(8000)
set @t=''
select @t=@t + ' SUM(CASE WHEN YF = ' + a.YF + ' THEN CPXSE1 ELSE 0 END) [CPXSE1 ' + a.YF + ' YF], SUM(CASE WHEN YF = ' + a.YF + ' THEN CPXSE2 ELSE 0 END) [CPXSE2 ' + a.YF + ' YF],'
FROM (SELECT CAST(YF as varchar(5)) YF FROM tbl GROUP BY YF ) a
select @t='SELECT DQ, ' + LEFT(@t, LEN(@t)-1) + ' FROM tbl GROUP BY DQ'
EXEC(@t)