MySQL平均销售价格排序表

时间:2020-08-10 12:39:23

标签: mysql sql

写一(1)个MySQL 查询语句返回“合同中”有合同规定的物业的平均售价 该机构开展业务的每个州过去一个月。结果应从最高到最高排序 平均售价最低。您的查询应返回以下格式的表 我尝试过

select * from(
select   avg(sale_price)  from  purchase where property_id = 64
union all  (
select   avg(sale_price)  from  purchase where property_id = 60)
union (
select avg(sale_price) from purchase where property_id = 58))  as i
order by  sale_price  ASC;

因为我的表中有sale_price列,所以出现了此错误

22:08:19选择* from(从购买商品中选择avg(sale_price),其中 property_id = 64全部合并(从购买中选择avg(sale_price) 其中property_id = 60)union(从购买中选择avg(sale_price) 其中property_id = 58)),因为我按sale_price ASC LIMIT 0订购, 1000错误代码:1054。“订单”中的未知列“ sale_price” 条款0.000秒

1 个答案:

答案 0 :(得分:1)

您应该在每个UNION的SELECT子句中使用别名。

SELECT 
  * 
FROM
  (SELECT 
    AVG(sale_price) AS sale_price 
  FROM
    purchase 
  WHERE property_id = 64 
  UNION
  ALL 
  (SELECT 
    AVG(sale_price)  AS sale_price 
  FROM
    purchase 
  WHERE property_id = 60) 
  UNION
  (SELECT 
    AVG(sale_price)  AS sale_price
  FROM
    purchase 
  WHERE property_id = 58)) AS i 
ORDER BY sale_price ASC ;

还是可以使用以下查询?我认为这在性能方面会更简单。

SELECT 
  AVG(sale_price) AS avg_sale_price 
FROM
  purchase 
WHERE property_id IN (64, 60, 58) 
GROUP BY property_id 
ORDER BY avg_sale_price ;