Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tsql union of sub queries that each require an ORDER BY clause

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.

like image 867
Jonathon Kresner Avatar asked Mar 01 '11 20:03

Jonathon Kresner


People also ask

Can ORDER BY clause be used in subquery?

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.

Can we use ORDER BY clause in UNION?

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.

Can we use ORDER BY clause in UNION in SQL Server?

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.

Can we use UNION in subquery?

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.


Video Answer


2 Answers

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
like image 186
PMC Avatar answered Oct 13 '22 19:10

PMC


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
like image 30
Joe Stefanelli Avatar answered Oct 13 '22 17:10

Joe Stefanelli