简体   繁体   English

Mysql 平均售价中的排序语句

[英]Mysql sorted statement in average sale price

Write one (1) MySQL query statement that returns the average sale price for properties that were 'under contract' in the past month for each State where the agency operates.编写一 (1) 个 MySQL 查询语句,返回该机构运营的每个 State 在过去一个月内“签订合同”的物业的平均销售价格。 The result should be sorted from highest to lowest by average sale price.结果应按平均售价从高到低排序。 Your query should return a table in the following format i tried您的查询应返回我尝试过的以下格式的表格

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;

i got this error as i have sale_price column in my table我收到此错误,因为我的表中有 sale_price 列

22:08:19 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 LIMIT 0, 1000 Error Code: 1054. Unknown column 'sale_price' in 'order clause' 0.000 sec 22:08:19 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))当我按 sale_price ASC LIMIT 0 订购时,1000 错误代码:1054。“订单条款”中的未知列“sale_price”0.000 秒

You should use an alias in the SELECT clause in every UNION.您应该在每个 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 ;

Or could you use the following query?或者您可以使用以下查询吗? I would think this is more straightforward on performance side.我认为这在性能方面更直接。

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 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM