我有一张表格列出了一些案例,并指定了主要和二级技术人员。我想要完成的是汇总技术人员作为主要和次要技术工作的案例数量。应该看起来像这样...
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
我已经做了一些搜索,但似乎无法找到问题的答案。
答案 0 :(得分: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
答案 1 :(得分: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;
答案 2 :(得分: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