mehdi nejati
mehdi nejati

Reputation: 346

having sum in nested select

I have two tables: one is Tour and other is ReservedTour. The columns of the tables are:

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

I write an SQL statement such as

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;

but this has an error — the total is not correct.

How can I correct this?

Upvotes: 2

Views: 8973

Answers (2)

sgeddes
sgeddes

Reputation: 62861

I think you might be looking for something like this:

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

Upvotes: 1

www
www

Reputation: 4391

Try this:

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

Upvotes: 1

Related Questions