我有一张表叫做#34; PassFailMaster"通过PassFail字段为1; 0表示失败。
我需要计算通过次数并失败并在同一行显示它们。我尝试了2个聚合和一个联合,但最终每个测试类型都有2行
这是一个数据样本:
CodeName CodeDesc TestNumber PassFail
v1 Vibration 1 0
V1 Vibration 2 0
v1 Vibration 3 1
s1 Shock 4 1
s1 Shock 5 1
s1 Shock 6 0
这是我的查询
SELECT CodeName, CodeDesc, COUNT(CodeName) AS PassValues, 0 as FailValues
FROM PassFailMaster
WHERE (PassFail = 1)
GROUP BY CodeName, CodeDesc
UNION
SELECT CodeName, CodeDesc, 0 AS PassValues, COUNT(CodeName) AS FailValues
FROM PassFailMaster
WHERE (PassFail = 0)
GROUP BY CodeName, CodeDesc
ORDER BY CodeName
这里的数据结果如下:
CodeName CodeDesc PassValues FailValues
s1 Shock 0 1
s1 Shock 2 0
v1 Vibration 0 2
v1 Vibration 1 0
我需要传球和结果的结果没有像这样结束一行。
CodeName CodeDesc PassValues FailValues
s1 Shock 2 1
v1 Vibration 1 2
有什么想法吗?
谢谢 - 迈克
答案 0 :(得分:0)
将您的查询用作第二个查询的数据源(即将其用作子查询):
select
codeName, codeDesc,
sum(a.passValues) as passValues, sum(a.failValues) as failValues
from
(
SELECT
CodeName, CodeDesc, COUNT(CodeName) AS PassValues, 0 as FailValues
FROM PassFailMaster
WHERE (PassFail = 1)
GROUP BY CodeName, CodeDesc
UNION
SELECT
CodeName, CodeDesc, 0 AS PassValues, COUNT(CodeName) AS FailValues
FROM PassFailMaster
WHERE (PassFail = 0)
GROUP BY CodeName, CodeDesc
) as a
group by codeName, codeDesc
ORDER BY CodeName
答案 1 :(得分:0)
你可以像这样有条件地聚合:
select codename
, codedesc
, sum(case when passfail = 1 then 1 else 0 end) as pass_values
, sum(case when passfail = 0 then 1 else 0 end) as fail_values
from passfailmaster
group by codename
, codedesc