SQL Server 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
我可以通过将结果导入临时表然后查询临时表来获得结果来实现我想要的结果,但这远非有效,我希望有更好的解决方案。
答案 0 :(得分:0)
您可以获取每个字段的MAX()。即:
ID a b c d
1 1 NULL NULL NULL
1 NULL 1 NULL NULL
1 NULL NULL 1 NULL
SELECT ID
, MAX(a) AS a
, MAX(b) AS b
, MAX(c) AS c
, MAX(d) as d
FROM Table
GROUP BY ID
结果:
ID a b c d
1 1 1 1 NULL
答案 1 :(得分:0)
做这样的事情:
select staff + convert(char(2),service_date,110) staff,
count(case when procedure like '90791%' then staff end) '90791',
count(case when procedure like '90832%' then staff end) '90832',
count(case when procedure like '90834%' then staff end) '90834',
count(case when procedure like '90837%' then staff end) '90837',
count(case when procedure like '90847%' then staff end) '90847'
from service_history
where program='OPCC'
....
group by staff + convert(char(2),service_date,110)
应该这样做!