日期:2014-05-18 浏览次数:20728 次
--> 测试数据:[table1] if object_id('[table1]') is not null drop table [table1] create table [table1]([mon] varchar(6),[dep] varchar(2),[yj] int) insert [table1] select '一月份','01',10 union all select '一月份','02',10 union all select '一月份','03',5 union all select '二月份','02',8 union all select '二月份','04',9 union all select '三月份','03',8 --> 测试数据:[table2] if object_id('[table2]') is not null drop table [table2] create table [table2]([dep] varchar(2),[dname] varchar(12)) insert [table2] select '01','国内业务一部' union all select '02','国内业务二部' union all select '03','国内业务三部' union all select '04','国际业务部' select b.dname 部门, SUM(case when [mon]='一月份' then [yj] end) as 一月份, SUM(case when [mon]='二月份' then [yj] end) as 二月份, SUM(case when [mon]='三月份' then [yj] end) as 三月份 from table1 a inner join table2 b on a.dep=b.dep group by b.dname /* 部门 一月份 二月份 三月份 国际业务部 NULL 9 NULL 国内业务二部 10 8 NULL 国内业务三部 5 NULL 8 国内业务一部 10 NULL NULL */
------解决方案--------------------
CREATE TABLE table1([月份mon] VARCHAR(20),[部分dep] VARCHAR(10),[业绩yj] INT) INSERT INTO table1 SELECT '一月份', '01', 10 UNION ALL SELECT '一月份', '02', 10 UNION ALL SELECT '一月份', '03' ,5 UNION ALL SELECT '二月份', '02' ,8 UNION ALL SELECT '二月份', '04' ,9 UNION ALL SELECT '三月份', '03' ,8 CREATE TABLE table2(部门dep VARCHAR(20), 部门名称dname VARCHAR(20)) INSERT INTO table2 SELECT '01', '国内业务一部' UNION ALL SELECT '02', '国内业务二部' UNION ALL SELECT '03', '国内业务三部' UNION ALL SELECT '04', '国际业务部' SELECT [部分dep],[一月份], [二月份], [三月份] FROM table1 PIVOT ( SUM([业绩yj]) FOR [月份mon] IN ([一月份], [二月份], [三月份]) ) AS p /*部分dep 一月份 二月份 三月份 ---------- ----------- ----------- ----------- 01 10 NULL NULL 02 10 8 NULL 03 5 NULL 8 04 NULL 9 NULL (4 行受影响) */
------解决方案--------------------
USE tempdb; GO IF OBJECT_ID('table1') IS NOT NULL DROP TABLE table1; GO IF OBJECT_ID('table2') IS NOT NULL DROP TABLE table2; GO CREATE TABLE table1 (mon VARCHAR(20), dep CHAR(5) , yj INT ); GO CREATE TABLE table2 (dep CHAR(5), dname VARCHAR(20)); GO INSERT INTO table1 VALUES('一月份','01',10); INSERT INTO table1 VALUES('一月份','02',10); INSERT INTO table1 VALUES('一月份','03',5); INSERT INTO table1 VALUES('二月份','02',8); INSERT INTO table1 VALUES('三月份','03',8); INSERT INTO table1 VALUES('二月份','04',9); INSERT INTO table2 VALUES('01','国内业务一部'); INSERT INTO table2 VALUES('02','国内业务二部'); INSERT INTO table2 VALUES('03','国内业务三部'); INSERT INTO table2 VALUES('04','国际业务部'); --查询 SELECT DISTINCT t1.dep,t2.yj AS '一月份' ,t3.yj AS '二月份',t4.yj AS '三月份' FROM tabl