SQL COUNT和子查询

时间:2016-03-15 22:09:49

标签: sql

我在编写以下查询时遇到问题: 找到战斗的名称,其中至少有3艘船的枪支数量低于9且其中至少有2艘有结果' ok'在战斗中参加。

enter image description here

这是表的关系,我认为查询应该是这样的:

 select o.BATTLE 
 from OUTCOMES o 
 join SHIPS s on o.SHIP = s.NAME
 join CLASSES c on s.CLASS = c.CLASS
 group by o.BATTLE
 having COUNT(case when 
            -- condition for ar least 3 ships with NUMGUNS < 9 and at least 2 of them with result = 'ok'
            then 1 else null end);

我在SQL方面相对较新,对我来说这不容易查询。 提前谢谢。

P.S。我使用MSSQL。

2 个答案:

答案 0 :(得分:5)

select o.BATTLE 
from OUTCOMES o 
join SHIPS s on o.SHIP = s.NAME
join CLASSES c on s.CLASS = c.CLASS
group by o.BATTLE    
having 
      COUNT(CASE WHEN c.NUMGUNS < 9 THEN 1 END) >= 3
  AND COUNT(CASE WHEN o.RESULT = 'OK' THEN 1 END) >= 2

您可以为readbilty添加ELSE NULL,但NULLCASE的默认值。

因为你的问题不清楚,你也可以考虑这个

having 
      COUNT(CASE WHEN  c.NUMGUNS < 9 THEN 1 END) >= 3
  AND COUNT(CASE WHEN (c.NUMGUNS < 9 AND o.RESULT = 'OK') THEN 1 END) >= 2
根据shawnt00的建议

编辑

select o.BATTLE 
from OUTCOMES o 
join SHIPS s on o.SHIP = s.NAME
join CLASSES c on s.CLASS = c.CLASS
WHERE c.NUMGUNS < 9
group by o.BATTLE    
having 
      COUNT(*) >= 3
  AND COUNT(CASE WHEN o.RESULT = 'OK' THEN 1 END) >= 2

答案 1 :(得分:0)

没有样本数据和您的预期结果,很难准确猜出您想要强加的逻辑,但这是我最好的猜测:

 select o.BATTLE 
 from OUTCOMES o 
 join SHIPS s on o.SHIP = s.NAME
 join CLASSES c on s.CLASS = c.CLASS
 group by o.BATTLE
 having COUNT(case when c.numguns<9 then 1 else null end)>=3 
    and COUNT(case when o.result='ok' then 1 else null end)>=2;