3

我有一个 sql 查询来显示 stage_time 表中所有 stage_times 的总和。但是我只需要对所有 3 个阶段都输入了值的汽车的 stage_times 总和,因此在这种情况下将 car_no 3 从列表中排除;

这是一个带有我的示例代码的 sqlfiddle http://sqlfiddle.com/#!2/1675d/78

SELECT d.*, SUM(Stage_Time) AS total
FROM Driver d, Stage_Times st
WHERE st.Driver_Id = d.Driver_Id AND st.Event_Id = 1 
      AND st.Stage_Id <= 3 
GROUP BY d.Driver_Id
ORDER BY total;

提前感谢您的帮助

4

2 回答 2

5

您可以只添加一个 Have 子句

having count(distinct st.Stage_id) = 3

查看更新的 sqlfiddle

(顺便说一句,我将您的查询更改为使用联接,这是一种更好的方法)。

于 2013-10-03T22:02:15.467 回答
0
select
  d.*
  , tt.TotalTime
from
  (
      select
        d.Driver_Id
        , SUM( st.Stage_Time ) TotalTime
      from
        Driver d
        inner join Stage_Times st
         on st.Driver_Id = d.Driver_Id
      where
        st.Event_Id = 1
      group by 
        d.Driver_Id
      having
        count(1) = 3
  ) tt
  inner join Driver d
   on tt.Driver_Id = d.Driver_id
于 2013-10-03T22:14:02.927 回答