MySQL:来自多个表的排名,子查询?

时间:2018-09-20 21:39:54

标签: mysql join group-by multiple-tables dbeaver

这是一个MySQL问题。我有三个带有以下各列的表:

transactions (table): transact_id, customer_id, transact_amt, product_id,
products (table): product_id, product_cost, product_name, product_category
customers (table): customer_id, joined_at, last_login_at, state, name, email

我想要一个查询,以找出每个州和州中最受欢迎的商品。棘手的部分之一是某些product_name具有多个product_id。因此,尽管我加入了三个产生两列输出的表:state和product_name。到这里为止,这样做很好:

SELECT p.product_name, c.state
FROM products p
INNER JOIN transactions t
ON p.product_id = t.product_id
INNER JOIN customers c
ON c.customer_id = t.customer_id

这将选择所有产品以及客户所在的州。问题是我找不到按州对mos热门产品进行排名的方法。我尝试了不同的group by,order by和使用子查询,但没有成功。我怀疑我需要进行子查询,但是找不到解决方法。预期结果应如下所示:

 most_popular_product | state
 Bamboo               | WA
 Walnut               | MO

任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要一个子查询来获取每种状态下每种产品的交易计数。

SELECT p.product_name, c.state, COUNT(*) AS count
FROM products p
INNER JOIN transactions t
ON p.product_id = t.product_id
INNER JOIN customers c
ON c.customer_id = t.customer_id
GROUP BY p.product_name, c.state

然后编写另一个将其作为子查询的查询,并获得每个状态的最高计数。

SELECT state, MAX(count) AS maxcount
FROM (
    SELECT p.product_name, c.state, COUNT(*) AS count
    FROM products p
    INNER JOIN transactions t
    ON p.product_id = t.product_id
    INNER JOIN customers c
    ON c.customer_id = t.customer_id
    GROUP BY p.product_name, c.state
) AS t
GROUP BY state

最后,将他们聚在一起:

SELECT t1.product_name AS most_popular_product, t1.state
FROM (
    SELECT p.product_name, c.state, COUNT(*) AS count
    FROM products p
    INNER JOIN transactions t
    ON p.product_id = t.product_id
    INNER JOIN customers c
    ON c.customer_id = t.customer_id
    GROUP BY p.product_name, c.state
) AS t1
JOIN (
    SELECT state, MAX(count) AS maxcount
    FROM (
        SELECT p.product_name, c.state, COUNT(*) AS count
        FROM products p
        INNER JOIN transactions t
        ON p.product_id = t.product_id
        INNER JOIN customers c
        ON c.customer_id = t.customer_id
        GROUP BY p.product_name, c.state
    ) AS t
    GROUP BY state
) AS t2 ON t1.state = t2.state AND t1.count = t2.maxcount

这与SQL select only rows with max value on a column基本上是相同的模式,只是将第一个分组查询用作要分组的表。