日期:2014-05-17 浏览次数:20610 次
--> 生成测试数据表: [a]
IF OBJECT_ID('[a]') IS NOT NULL
DROP TABLE [a]
GO
CREATE TABLE [a] ([员工代码] [int],[姓名] [nvarchar](10))
INSERT INTO [a]
SELECT '1','王x' UNION ALL
SELECT '2','李x'
--> 生成测试数据表: [b]
IF OBJECT_ID('[b]') IS NOT NULL
DROP TABLE [b]
GO
CREATE TABLE [b] ([任务编号] [int],[员工代码] [int],[性质] [nvarchar](10))
INSERT INTO [b]
SELECT '1','1','主管' UNION ALL
SELECT '2','1','分管' UNION ALL
SELECT '3','1','主办' UNION ALL
SELECT '4','1','协办' UNION ALL
SELECT '5','1','协办' UNION ALL
SELECT '2','2','分管' UNION ALL
SELECT '3','2','主办' UNION ALL
SELECT '4','2','协办' UNION ALL
SELECT '5','2','协办'
-->SQL查询如下:
SELECT a.*,b.主管,b.分管,b.主办,b.协办
FROM [a] a
JOIN (
SELECT *
FROM (select 员工代码,性质 from b) b
PIVOT(COUNT(性质) FOR 性质 IN(主管,分管,主办,协办)) P
) b
ON a.员工代码=b.员工代码
/*
员工代码 姓名 主管 分管 主办 协办