Exercise #77

Find the dates where number of trips from town Rostov were the maximum. Result set: number of trips, date.

It seemed to me, that the formulation is extremely clear. When this exercise still was at the second stage, it did not cause any questions. The difference in class I suppose :-). Now however the necessity to answer similar questions arises so often that I had to write this FAQ.

Here a typical example of wrong query:

  1. SELECT MAX(superden.qty), superden.date
  2. FROM
  3. (SELECT COUNT(den.trip_no) AS qty, den.date
  4. FROM
  5. (SELECT DISTINCT trip_no, date FROM Pass_in_trip) AS den,
  6. Trip WHERE trip.trip_no=den.trip_no AND
  7. trip.town_from='Rostov'
  8. GROUP BY den.date) AS superden
  9. GROUP BY superden.date;

The subquery

  1. SELECT DISTINCT trip_no, date FROM Pass_in_trip;
defines the flights which have been carried out. DISTINCT here it is quite pertinent, because the combination {trip_no, date} is the same for the passengers that flew in one plane. The subquery is joining with the Trip table to select only the Rostov flights: trip.town_from ='Rostov '.

The grouping by date allows us to count up distribution of number of the Rostov flights by days. While all is true, but last step is absolutely senseless. What for one more grouping by date is needed if all is already grouped, i.e. result set includes only one row for each date?

It seems, that the author of the above solution thus tried to find a maximum, but has received the same set. Let us take sample distribution of flights number by dates:

2007-08-19     2
2007-08-20     2
2007-08-21     3

In accordance with the task formulation we should receive only one row:

2007-08-21     3
as the maximal value of number of flights (3) is reached at 2007-08-21, but we shall receive the same 3 rows as a result of last grouping by date.

I hope now that it is clear what you should do to solve this problem, and I'll not answer more letters on this occasion :-).

To solve the problem on SQL-EX.RU

Bookmark and Share
aggregate functions Airport ALL AND AS keyword ASCII AVG Battles Bezhaev Bismarck C.J.Date calculated columns Cartesian product CASE cast CHAR CHARINDEX Chebykin check constraint classes COALESCE common table expressions comparison predicates Computer firm CONSTRAINT CONVERT correlated subqueries COUNT CROSS APPLY CTE data type conversion data types database schema DATEADD DATEDIFF DATENAME DATEPART DATETIME date_time functions DDL DEFAULT DEFAULT VALUES DELETE DISTINCT DML duplicates edge equi-join EXCEPT exercise (-2) More tags
The book was updated
month ago
©SQL-EX,2008 [Evolution] [Feedback] [About] [Links] [Team]
All right reserved.