Selecting data from a sub query
-
16-01-2021 - |
Question
I am doing the exercises this is the link (https://www.wiseowl.co.uk/sql/exercises/standard/subqueries/4228/). Can anyone help me. Thanks in advance!
Question
Write a SELECT
statement to return events from the 3 continents with the fewest events.
Help
To do this first write a SELECT
query which returns all the continents and events.
Subquery select
Unsorted results returns 459 events.
Now underneath write another SELECT
statement which lists events for the 3 continents with the lowest COUNT
of events. Put the COUNT
in the ORDER BY
clause, not the SELECT
.
Finally use the second SELECT
as a filter in the first SELECT
's WHERE
clause. To do this use ContinentName IN (subquery)
.
Subquery Continent
Only 8 events in these 3 continents - maybe stick to Ibiza and the Islands!
My query
Select [ContinentName], [EventName]
from tblevent a
join[dbo].[tblCountry] c on a.[CountryID]=c.[CountryID]
join [dbo].[tblContinent] b on c.[ContinentID]=b.[ContinentID]
where [ContinentName] in
(
select top 3 [ContinentName]
from tblevent a join[dbo].[tblCountry] c on a.[CountryID]=c.[CountryID]
join [dbo].[tblContinent] b on c.[ContinentID]=b.[ContinentID]
group by [ContinentName]
)
order by count([EventName])
Result:
Error message when I run above query:
Column 'dbo.tblContinent.ContinentName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
The problem goes away if I remove the order by count([EventName])
but I need events from 3 continents with the fewest events, so order by count([EventName])
must be there. There is some other problem causing the error.
Solution
The error is due to using COUNT()
in a query without GROUP BY
- which means GROUP BY ()
- and at the same time having some columns in the SELECT
list. You need to move that COUNT()
in the subquery.
Assuming you want to show all Events from the 3 continents with lowest count of events:
Select c.[ContinentName], a.[EventName]
from tblevent a
join [dbo].[tblCountry] c
on a.[CountryID] = c.[CountryID]
join [dbo].[tblContinent] b
on c.[ContinentID] = b.[ContinentID]
where [ContinentName] in
(
select top 3 [ContinentName]
from tblevent a
join [dbo].[tblCountry] c
on a.[CountryID] = c.[CountryID]
join [dbo].[tblContinent] b
on c.[ContinentID] = b.[ContinentID]
group by [ContinentName]
order by count(*)
) ;