1

我有一张表格,列出了一些案例并分配了初级和二级技术人员。我想要完成的是汇总技术人员作为初级和二级技术工作的案例数量。应该是这个样子...

Technician     Primary     Secondary
John             4              3
Stacy            3              1
Michael          5              3

我从中提取数据的表如下所示:

CaseID, PrimaryTech, SecondaryTech, DOS

以前我用过这样的东西,但现在我的上级也在询问二次病例的数量……

SELECT PrimaryTech, COUNT(CaseID) as Total
GROUP BY PrimaryTech

我做了一些搜索,但似乎无法找到我的问题的答案。

4

3 回答 3

1
Select Tech, 
       sum(case when IsPrimary = 1 then 1 else 0 end) as PrimaryCount,
       sum(case when IsPrimary = 0 then 1 else 0 end) as SecondaryCount
from
(
  SELECT SecondaryTech as Tech, 0 as IsPrimary
  FROM your_table
  union all
  SELECT PrimaryTech as Tech, 1 as IsPrimary
  FROM your_table
) x
GROUP BY Tech
于 2013-11-11T19:15:52.833 回答
0
SELECT COALESCE(A.NAME, B.NAME) AS NAME, CASE WHEN A.CASES IS NOT NULL THEN A.CASES ELSE 0 END AS PRIMARY_CASES,
CASE WHEN B.CASES IS NOT NULL THEN B.CASES ELSE 0 END AS SECONDARY_CASES
FROM
(
SELECT COUNT(*) AS CASES, PRIMARYTECH AS NAME FROM YOUR_TABLE
GROUP BY PRIMARYTECH
) AS A
FULL OUTER JOIN
(
SELECT COUNT(*) AS CASES, SECONDARYTECH AS NAME FROM YOUR_TABLE
GROUP BY SECONDARYTECH
) AS B
ON A.NAME = B.NAME
于 2013-11-11T19:35:23.537 回答
0

您可以将两个子查询与 FULL JOIN 组合在一起,如此SQLFiddle中所示。

SELECT Technician = COALESCE(pri.Technician, sec.Technician)
    , PrimaryTech
    , SecondaryTech
FROM 
    (SELECT Technician = PrimaryTech
        , PrimaryTech = COUNT(*)
    FROM Cases
    WHERE PrimaryTech IS NOT NULL
    GROUP BY PrimaryTech) pri
FULL JOIN
    (SELECT Technician = SecondaryTech
        , SecondaryTech = COUNT(*)
    FROM Cases
    WHERE SecondaryTech IS NOT NULL
    GROUP BY SecondaryTech) sec
    ON pri.Technician = sec.Technician
ORDER By Technician;
于 2013-11-11T19:25:33.767 回答