Sorting a Union query

时间:2017-08-05 10:59:23

标签: sql sql-order-by

I have a pc, laptop and printer table, each of them having a price and model field.

I want to create a combined view of price and model number from these three tables, sorted by price. I have the following query:

SELECT p.model, p.price FROM ( 
  SELECT price, model FROM laptop  
    UNION  
  SELECT price, model  FROM pc 
    UNION 
  SELECT price, model  FROM printer    
 ) 
AS p order by p.price desc

Running this query does not sort on price, instead it returns the results sorted on model number. I checked similar question, but unable to make my query sort on price field.

model   price
1121    850.0000
1232    350.0000
1232    400.0000
1232    600.0000
1233    600.0000
1233    950.0000
1233    970.0000
1233    980.0000
1260    350.0000
1276    400.0000
1288    400.0000
1298    1050.0000
1298    700.0000
1298    950.0000
1321    970.0000
1401    150.0000
1408    270.0000
1433    270.0000
1434    290.0000
1750    1200.0000
1752    1150.0000

2 个答案:

答案 0 :(得分:0)

you could order direcly this way

SELECT price, model FROM laptop  
UNION  
SELECT price, model  FROM pc 
UNION 
SELECT price, model  FROM printer 
order by price desc 

could be you have string so try

SELECT price, model FROM laptop  
UNION  
SELECT price, model  FROM pc 
UNION 
SELECT price, model  FROM printer 
order by cast(price AS decimal(10,4)) desc 

or for the ide you are using

select * from ( 
SELECT price, model FROM laptop  
UNION  
SELECT price, model  FROM pc 
UNION 
SELECT price, model  FROM printer  ) t
order by cast(price AS decimal(10,4)) desc 

答案 1 :(得分:0)

First, I would suggest that you use union all rather than union. It has better performance, because it does not incur overhead for removing duplicates.

Second, you can do this by adding order by:

SELECT price, model FROM laptop  
UNION ALL
SELECT price, model FROM pc 
UNION ALL
SELECT price, model FROM printer    
ORDER BY price DESC;

Some databases don't allow ORDER BY on union queries. In that case, a subquery is necessary:

SELECT model, price
FROM (SELECT price, model FROM laptop  
      UNION ALL
      SELECT price, model FROM pc 
      UNION ALL
      SELECT price, model FROM printer 
     ) pm   
ORDER BY price DESC;

This is essentially the query in your question. It should do what you intend.