代码之家  ›  专栏  ›  技术社区  ›  user28577345

每个产品的最高评价客户

  •  0
  • user28577345  · 技术社区  · 1 年前

    每个产品的最高评价客户

    使用桌子 playground.product_reviews ,编写一个SQL查询,为每个产品标识提供 highest review score 。如果在评论得分中有平局,则得票最多的客户应被视为最有帮助的客户。输出应包括以下列 product_id , customer_id , review_score ,以及 helpful_votes ,按升序捕获每个订购产品的顶部评论的详细信息 product_id

    以下是用于查询此问题的表格:

    CREATE TABLE playground.product_reviews
    (
        seller_id int,
        customer_id int,
        product_id int,
        review_date date,
        review_score double,
        helpful_votes int
    )
    
    INSERT INTO playground.product_reviews
    (
        seller_id int,
        customer_id int,
        product_id int,
        review_date date,
        review_score double,
        helpful_votes int
    )
    values
    (301, 202, '2024-01-04', 4.5, 1)
    ,(301, 202, '2024-02-05', 4.6, 12)
    ,(302, 203, '2024-02-05', 4.8, 5)
    ,(303, 204, '2024-02-05', 3.5, 12)
    ,(301, 202, '2024-03-05', 2.5, 12)
    ,(302, 203, '2024-01-04', 4.5, 7)
    ,(303, 204, '2024-01-04', 4.5, 8)
    ,(301, 204, '2024-01-04', 4.5, 12)
    ,(302, 203, '2024-03-04', 4.5, 8)
    ,(303, 204, '2024-03-04', 4.5, 12)
    

    您的答案应包括以下列:

    product_id integer
    customer_id integer
    review_score double
    helpful_votes integer
    

    我的SQL是-

    with Ordered_Data AS
    (
    SELECT 
    *,
    RANK() OVER (Partition by customer_id order by review_score, helpful_votes desc) as r
    FROM playground.product_reviews
    ) 
    select 
    product_id,
    customer_id,
    review_score,
    helpful_votes
    from Ordered_Data
    where r = 1
    order by product_id asc
    

    但我得到了错误的答案,最低的复习分数获得了最高的排名。我错过了什么?

    1 回复  |  直到 1 年前
        1
  •  2
  •   Tushar Kesarwani    1 年前

    代码中的问题是你有 DESC 只有在 helpful_votes rank()函数的工作原理是按列对所有顺序进行排序。因此,在您的查询中,评论将主要根据review_score按升序排列。

    WITH ordered_data
         AS (SELECT *,
                    Rank()
                      OVER (
                        partition BY customer_id
                        ORDER BY review_score DESC, helpful_votes DESC) AS r
             FROM   playground.product_reviews)
    SELECT product_id,
           customer_id,
           review_score,
           helpful_votes
    FROM   ordered_data
    WHERE  r = 1
    ORDER  BY product_id ASC