1

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

我想要的结果可以通过将结果导入临时表然后查询临时表来获得结果,但这远没有效率,我希望有更好的解决方案。

4

2 回答 2

0

您可以获取每个字段的 MAX() 。IE:

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
于 2013-07-19T20:51:19.567 回答
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)

应该这样做!

于 2013-07-19T20:56:06.973 回答