【问题标题】:how to calculate weighted average in hql?如何计算hql中的加权平均值?
【发布时间】:2021-05-02 12:50:26
【问题描述】:

我是 HQL 的新手,我有一张桌子:

  1. A栏对应商家名称,
  2. B栏>>商户ID
  3. C 栏 >> 承诺发货(以工作日为单位)[指定发货日]
  4. column D >> nr 商家在发货日基础上拥有的 SKU [named Listing_count]
  5. E栏>>对应于该商家[named total_listingcount]的SKU总数

有没有像我在 Excel 上那样使用 HiveQL 计算每个商家的加权发货日平均值的简单查询? (由于发货天数可能不同,并非每个商家的行数都相同)

【问题讨论】:

    标签: sql hive hql hiveql


    【解决方案1】:

    您需要使用sum() over(order by time rows between preceding 4 and current row)的窗口功能。

    SELECT
        merchantName,
        merchantID,
        shipmentday,
        listing_count,
        sum(shipmentday * listing_count) over(order by period rows between preceding 4 and current row) / sum(listing_count) over(order by period rows between preceding 4 and current row) as weighed_ma
    FROM (
        SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS period
        FROM your_table
    );
    

    注意:如果数据中有时间列,则可以忽略子查询。我正在生成period,因为您的示例中没有时间列。

    如果窗口函数抛出错误,那么我假设您的 Hive 版本不支持所需的窗口函数。或者,您可以使用CROSS JOIN。 CROSS JOIN 将原始表中的所有行映射到目标表中的所有行(将其视为没有任何键匹配的左连接)。

    WITH a AS (
        SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS period
        FROM your_table
    )
    
    SELECT
        merchantName,
        merchantID,
        shipmentday,
        listing_count,
        sum(shipmentday_b * listing_count_b) / sum(listing_count_b) AS weighted_ma
    FROM (
        SELECT 
            a.*, 
            b.shipmentday AS shipmentday_b, 
            b.listing_count AS listing_count_b
        FROM a
        CROSS JOIN a AS b
        WHERE b.rn BETWEEN a.rn - 4 and a.rn
    ) a
    GROUP BY merchantName, merchantID, shipmentday,listing_count;
    

    【讨论】:

    • 谢谢,但它抛出错误:编译语句时出错:失败:ParseException 行 6:71 无法识别 windowframeboundary 中的“preceding”“4”“和”附近的输入,顺便说一句,shipmentday 信息是静态的SKU,不生成周期就不能计算吗?
    • 选择商家名称,sum(shipmentday * Listing_count) / sum(listing_count) over (partition by Merchantname) as weighted_ma from my_table 计算正确,但商家名称重复,有什么方法可以避免重复记录吗?我不能在查询中使用 group by
    • 如果订购了shipmentday,则可以根据shipmentday订购
    • 为了避免重复使用SELECT DISTINCT * FROM ( <your query> ) a
    猜你喜欢
    • 2010-10-04
    • 1970-01-01
    • 2012-06-14
    • 2017-01-06
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 2016-12-14
    相关资源
    最近更新 更多