Monday, September 9, 2013

SQL: Can’t figure out Query and Sub-Queries

SQL: Can't figure out Query and Sub-Queries

I'm having trouble figuring this problem out. I'm doing some revision
exercises for university and would like to understand this BEFORE my exam
in 2 days.
I've attempted some things (which I'll post at the end). Please be kind,
this is my first Database subject so my attempts may seem very stupid to
you.
The question is as follows: Which artist/s has/have the largest number of
shows on at the moment? Show the First & Last Name of the artist/s and
their Address. ORDER BY clause cannot be used. Write a single SQL
Statement. Use Sub-Queries.
Relevant tables in the database:
Shows (ShowName, ArtistId, ShowStartDate, ShowEndDate)
Artists (ArtistId, FirstName, FamilyName, Address, PhoneNum)
We assume ArtistId, ShowStartDate, FirstName, FamilyName and Address
cannot be null.
Now, I think that I have to count the number of shows each artist has on
at the moment. Then, get the ArtistId for the artist/s that has/have the
most. Use the ArtistId to retrieve the artist details (names and address).
I got as far as this (which is very wrong):
SELECT FirstName, FamilyName, Address
FROM Artists
WHERE ArtistId = (SELECT ArtistId
FROM Shows
WHERE ArtistId = (SELECT MAX(Counted)
FROM (SELECT ArtistId, COUNT(ArtistId)
AS Counted
FROM Shows
WHERE ShowEndDate IS null
GROUP BY ArtistId)
GROUP BY ArtistId));
Well, I know
SELECT ArtistId, COUNT(ArtistId)
FROM Shows
WHERE ShowEndDate IS null
GROUP BY ArtistId
gives me a table with the count of how many times each ArtistId is listed.
Which is good. But from this results table, I need to get the ArtistId/'s
of the ones that have the highest count.
And this is where I'm lost.
Anyone can shed some light?
(As for which DBMS I am using: We have to use one created and supplied by
the university. It's very basic SQL. Simpler than Access 2010).
Thank you

No comments:

Post a Comment