联合中的SQL查询变量+ COUNT()

时间:2016-07-22 04:46:57

标签: sql sql-server

我需要帮助我需要

的SQL查询
 SELECT MachineID from TABLE1

然后

Count(Passfail) from TABLE2 WHERE MachineID= *MACHINEID
先前

from the SELECT语句到单个表中

1 个答案:

答案 0 :(得分:0)

你几乎把它写在那里。你需要阅读一些关于连接和sql group by的信息:

select T1.MachineId, count(T2.Passfail) from
Table1 T1 inner join Table2 T2 on T1.MachineId = T2.Machine Id
group by T1.MachineId

编辑: 对于根据PassFail值的单独计数,我使用:

select T1.MachineId, 
sum(case when T2.PassFail='pass' then 1 else 0 end) as 'pass',
sum(case when T2.PassFail='fail' then 1 else 0 end) as 'fail'
from Table1 T1 inner join 
Table2 T2 on T1.MachineId = T2.machineId 
group by T1.machineId