sql如何为每个州选择最受欢迎的商品

时间:2019-06-26 09:52:47

标签: postgresql group-by greatest-n-per-group

表架构:

customers
|_state

products
|_product_name

transactions
|_product_id

如何在每个州/州/州/州/州/州名称返回最流行商品的名称?

这是最接近的工作示例。

SELECT state, products.product_name, COUNT(products.product_name)
FROM customers INNER JOIN transactions ON customers.customer_id = transactions.customer_id
INNER JOIN products ON transactions.product_id=products.product_id
GROUP BY state, products.product_name;

给出每个州的所有产品,如下所示:

 state      name        name count  
 "AK"    "product1"        "1"
 "AK"    "product2"        "4"
 "AK"    "product3"        "1"
 "AR"    "product2"        "1"
 "AR"    "product2"        "2"

再次,我只希望每个州的计数最高。

1 个答案:

答案 0 :(得分:0)

在给定的查询中使用MAX()将给您期望的结果,每个州的最高计数。

有效查询将是:

SELECT state, MAX(PCount) AS HighestCount
FROM (
    SELECT state, products.product_name, COUNT(products.product_name) AS PCount
    FROM customers 
    INNER JOIN transactions ON customers.customer_id = transactions.customer_id
    INNER JOIN products ON transactions.product_id = products.product_id
    GROUP BY state, products.product_name
) Q
GROUP BY state