【问题标题】:Find the max amount of all averaged results in MySQL (BigQuery)在 MySQL (BigQuery) 中查找所有平均结果的最大数量
【发布时间】:2015-06-30 21:43:27
【问题描述】:

我按天计算了物业的平均价格。我想找到平均每日房价最高的房产:

select Prop_Name as property, arrival_date as arrival, round(avg(Rate)) as rate
from [SomeDataBase] 
where [Timestamp] >= '2015-06-15 00:00:00.000' 
and [Timestamp] <= '2015-06-20 23:59:59.000'  
group by property, arrival 
order by arrival asc limit 10;

所以我返回以下内容:

Property             Date              Rate
Prop_One    2015-06-15 00:00:00 UTC    281.0     
Prop_Two    2015-06-15 00:00:00 UTC    343.0     
Prop_Three  2015-06-15 00:00:00 UTC    266.0     
Prop_One    2015-06-15 00:00:00 UTC    87.0  
Prop_Three  2015-06-15 00:00:00 UTC    132.0     
Prop_Two    2015-06-15 00:00:00 UTC    80.0 

我想返回每天的最高费率而不重复:

Prop_Three  2015-06-15 00:00:00 UTC    400.0     
Prop_One    2015-06-16 00:00:00 UTC    586.0     
Prop_Three  2015-06-17 00:00:00 UTC    190.0     
Prop_Two    2015-06-18 00:00:00 UTC    180.0    

【问题讨论】:

    标签: mysql sql google-bigquery


    【解决方案1】:

    我认为 bigquery 支持row_number(),所以我认为这会起作用:

    select t.*
    from (select Prop_Name as property, arrival_date as arrival,
                 round(avg(Rate)) as rate,
                 row_number() over (partition by arrival_date order by avg(rate) desc) as seqnum
          from [SomeDataBase] 
          where [Timestamp] >= '2015-06-15' and
                [Timestamp] < '2015-06-21'  
          group by property, arrival 
         ) t
    where seqnum = 1;
    

    编辑:

    啊。以上是标准 SQL,但以下可能适用于 Bigquery:

    select t.*
    from (select t.*,
                 row_number() over (partition by arrival_date order by rate desc) as seqnum
          from (select Prop_Name as property, arrival_date as arrival,
                       round(avg(Rate)) as rate
                from [SomeDataBase] 
                where [Timestamp] >= '2015-06-15' and
                      [Timestamp] < '2015-06-21'  
                group by property, arrival 
               ) t
         ) t
    where seqnum = 1;
    

    【讨论】:

    • 我收到以下错误:“在分析表达式中,ORDER BY 必须引用命名列。找到 AVG”
    • @FF4Fanatic 这通常会出现在一个新问题下,而不是对答案的评论。在任何情况下,您都可能需要重命名作为您的 AVG 的列(例如,选择 avg(rate) as arate 之类的东西),然后按 arate 排序。你不能在 orderby 中有一个函数,它需要是一个被调用的列。如果需要,您始终可以使用嵌套子查询将您的 avg 转换为命名列
    • @Patrice。 . .在我看来,这是一个完全合理的评论。原始查询使用 BigQuery 不支持的 ANSI 标准 SQL 语法。希望它支持修改后的查询。
    • 即使修改后的查询在 BQ 中也不起作用,因为 BQ 希望 ORDER BY 内部窗口函数仅使用列名,而不是表达式。
    • @MoshaPasumansky 。 . .谢谢你。这在任何数据库中都是不正确的,因为那里不适合聚合函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2014-06-11
    相关资源
    最近更新 更多