Given the following tables:
shows:
title | basic_ticket_price
----------------+--------------------
Inception | $3.50
Romeo & Juliet | $2.00
performance:
perf_date | perf_time | title
------------+-----------+----------------
2012-08-14 | 00:08:00 | Inception
2012-08-12 | 00:12:00 | Romeo & Juliet
booking:
ticket_no | perf_date | perf_time | row_no | person_id
-----------+------------+-----------+--------+-----------
1 | 2012-08-14 | 00:08:00 | P01 | 1
2 | 2012-08-12 | 00:12:00 | O05 | 4
3 | 2012-08-12 | 00:12:00 | A01 | 2
And an additional table: seat which contains a list of seats numbered like that of row_no in booking with an area name.
Having grouped the booked seats using this statement:
select count(row_no) AS row_no,
area_name
from seat
where exists (select row_no
from booking
where booking.row_no = seat.row_no)
group by area_name;
which produces:
row_no | area_name
--------+--------------
1 | rear stalls
2 | front stalls
How can I now use the counted rows and area_name to write a single SQL statement to produce a list showing the names of shows, dates and times of performances, and the number of booked seats in each area?
I've tried this:
select s.title,
perf_date,
perf_time,
count(row_no) AS row_no,
area_name
from shows s,
performance,
seat
where exists (select row_no
from booking
where booking.row_no = seat.row_no)
group by area_name,s.title,performance.perf_date,performance.perf_time;
But it shows repeated rows:
title | perf_date | perf_time | row_no | area_name
----------------+------------+-----------+--------+--------------
Romeo & Juliet | 2012-08-12 | 00:12:00 | 1 | rear stalls
Romeo & Juliet | 2012-08-14 | 00:08:00 | 2 | front stalls
Inception | 2012-08-12 | 00:12:00 | 1 | rear stalls
Inception | 2012-08-14 | 00:08:00 | 2 | front stalls
Inception | 2012-08-14 | 00:08:00 | 1 | rear stalls
Inception | 2012-08-12 | 00:12:00 | 2 | front stalls
Romeo & Juliet | 2012-08-14 | 00:08:00 | 1 | rear stalls
Romeo & Juliet | 2012-08-12 | 00:12:00 | 2 | front stalls
(8 rows)
Any help with solving this would be appreciated.
JOIN ...perf_dateis actually an acceptable choice for an identifier. You wouldn't want to abuse a type name as column name. Apart from that, it really should be atimestamp. I'll add an answer.