考虑下表:PostgreSQL的select语句
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
和一个额外的表:座位包含的编号一样,row_no在预订与区域名称的座位名单。
已经分组使用此语句所预订的座位:
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;
主要生产:
row_no | area_name
--------+--------------
1 | rear stalls
2 | front stalls
我怎么能现在使用的计数行和AREA_NAME编写一个SQL语句来产生一个列表显示节目名称,演出日期和时间以及每个区域的预订座位数量?
我已经试过这样:
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;
,但它显示重复行:
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)
与解决任何帮助,将不胜感激。
另外:你缺少你的第二个连接条件声明。它将在节目,表演和座位之间形成一个笛卡尔连接。你最好用'JOIN ...'重写# – 2012-03-25 11:41:40
请接受我的道歉,我使用的是psql,但也标记了它,因为我发现大部分语句与select语句类似。 – 2012-03-25 11:47:28
您应该使用串行作为主键。如果你有第二个放映电影的空间?您不能让两部电影同时发生,因为它们由perf_date和perf_time标识。或者当表演安排时该怎么做?你必须修改多个表,这是一件坏事。还有一个小小的建议:我不会在列名中重复表格标题。否则你以perf.perf_title结束 - perf.title就足够了。 – 2012-03-25 13:15:38