在嵌套选择中得到总和

时间:2013-03-09 18:16:46

标签: sql

我有两个表:一个是Tour,另一个是ReservedTour。表的列是:

Tour       | ReservedTour
===========|=============
id         | id
city       | Tid
capacity   | number
timeout    | .
.          | .
.          | .
.          |
========== |======

我写了一个SQL语句,比如

select *, (select sum(rt.`number`) from ReservedTour as rt where rt.`Tid`=t.id GROUP BY rt.`Tid`) as total
  from Tour as t 
 where City = 'alahom' and '1400-12-13' <= t.`timeout` and 4 < t.`Capacity`- total;

但这有错误 - 总数不正确。

我该如何纠正?

2 个答案:

答案 0 :(得分:1)

试试这个:

select t.*, sum(rt.`number`) as total 
from Tour as t
join  ReservedTour as rt on rt.`Tid`=t.id
where City = 'alahom' and  t.`timeout`=> '1400-12-13' and t.`Capacity`-total > 4
GROUP BY t.id

答案 1 :(得分:0)

我想你可能正在寻找这样的东西:

SELECT T.*, RT.total
FROM Tour T
  JOIN (select Tid, sum(number) total
          from ReservedTour 
          GROUP BY TId ) RT ON T.Id = RT.TiD
WHERE City = 'alahom' 
   AND '1400-12-13' <= t.`timeout` 
   AND 4 < t.Capacity-RT.total;

Condensed SQL Fiddle Demo