Hi I apologize if the answer for this is somewhere else. I looked around and I could not see a simple solution. I have a query that I would like to run. I don't care about the order of the union set, only that the inner queries return the correct data which is the "Largest Areas".
(SELECT TOP 5 * FROM [geo].[Areas] WHERE CountryID = @CountryID AND (TypeID = 'City')
ORDER BY [ShapeArea] DESC) as BiggestCities
UNION ALL
(SELECT TOP 5 * FROM [geo].[Areas] WHERE CountryID = @CountryID AND (TypeID = 'National park')
ORDER BY [ShapeArea] DESC) as BiggestParks
But T-sql won't let me have ORDER BY on the sub-queries, only on the whole Union... Help appreciated! I would really prefer not to have to create temporary tables or anything like that.
An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery.
Union is a type of operator in MySQL. We can use ORDER BY with this to filter records. Use UNION if you want to select rows one after the other from several tables or several sets of rows from a single table all as a single result set. Let us see an example.
SQL Server will give error if ORDER BY is used inside a subquery of a UNION operator. MySQL will ignore the ORDER BY clause inside a subquery of a UNION operator.
You can use the UNION and UNION ALL operators in subqueries of SELECT statements within the WHERE clause, the FROM clause, and in collection subqueries.
Try this
SELECT *
FROM (SELECT TOP 5 *
FROM [geo].[Areas]
WHERE CountryID = @CountryID
AND (TypeID = 'City')
ORDER BY [ShapeArea] DESC) as BiggestCities
UNION ALL
SELECT *
FROM (SELECT TOP 5 *
FROM [geo].[Areas]
WHERE CountryID = @CountryID
AND (TypeID = 'National park')
ORDER BY [ShapeArea] DESC) as BiggestParks
SELECT t.* /* Excluding RowNum */
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY TypeID ORDER BY [ShapeArea] DESC) as RowNum
FROM [geo].[Areas]
WHERE CountryID = @CountryID
AND TypeID IN ('City', 'National park')
) t
WHERE t.RowNum <= 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With