SQL 服务器 2005
我正在尝试压缩结果集以使每个员工拥有一行数据,我的查询是
SELECT Staff +'- '+ CONVERT(CHAR(2),Service_Date, 110) AS Staff
,(SELECT COUNT (Procedure_) WHERE Procedure_ Like '90791%' ) AS '90791'
,(SELECT COUNT (Procedure_) WHERE Procedure_ Like'90832%' ) AS '90832'
,(SELECT COUNT (Procedure_) WHERE Procedure_ Like'90834%' ) AS '90834'
,(SELECT COUNT (Procedure_) WHERE Procedure_ Like'90837%' ) AS '90837'
,(SELECT COUNT (Procedure_) WHERE Procedure_ Like '90847%') AS '90847'
FROM dbo.Service_History
WHERE Program='OPCC'
AND STATUS='Kept'
AND TYPE = 'Client'
AND Procedure_ IS NOT NULL
AND Service_date BETWEEN DATEADD(mm, DATEDIFF(mm, 0,GETDATE())-3, 0) AND GETDATE()
GROUP BY Staff +'- '+ CONVERT(CHAR(2),Service_Date, 110),Procedure_
ORDER BY Staff +'- '+ CONVERT(CHAR(2),Service_Date, 110),Procedure_
GROUP BY Staff +'- '+ CONVERT(CHAR(2),Service_Date, 110),Procedure_
ORDER BY Staff +'- '+ CONVERT(CHAR(2),Service_Date, 110),Procedure_
结果集如下:(每个员工一行,返回一列数据,一列全为 NULL 行)。
Staff 90791 90832 90834 90837 90847
Smith, Joe (568)- 04 15 NULL NULL NULL NULL
Smith, Joe (568)- 04 NULL NULL 2 NULL NULL
Smith, Joe (568)- 04 NULL NULL NULL 1 NULL
Smith, Joe (568)- 04 NULL NULL NULL NULL NULL
我想将上述结果减少到一行。基本上每个员工每月一行,总计执行的程序数。
像这样:
Staff 90791 90832 90834 90837 90847
Smith, Joe (568)- 04 15 NULL 2 1 NULL
我想要的结果可以通过将结果导入临时表然后查询临时表来获得结果,但这远没有效率,我希望有更好的解决方案。