我有一个sql查询来显示stage_time表中stage_times的所有总和。但是我只需要为所有3个阶段输入值的汽车的阶段时间总和,所以在这种情况下car_no 3被排除在列表之外;
这是一个带有我的示例代码http://sqlfiddle.com/#!2/1675d/78
的sqlfiddleSELECT 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;
提前感谢您提供任何帮助
答案 0 :(得分:5)
您可以添加一个Having子句
having count(distinct st.Stage_id) = 3
请参阅更新的sqlfiddle
(顺便说一下,我改变了你的查询以使用join,这是一个更好的方法)。
答案 1 :(得分: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