MySQL: 多表排序,子查询?

MySQL: Ranking from multiple tables, sub queries?

这是一个 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

这会选择所有产品,以及客户所在的州。问题是我找不到对每个州最受欢迎的产品进行排名的方法。我尝试了不同的分组依据、排序依据和使用子查询,但都没有成功。我怀疑我需要做子查询,但我找不到解决它的方法。预期结果应如下所示:

 most_popular_product | state
 Bamboo               | WA
 Walnut               | MO

任何帮助将不胜感激。

谢谢!

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

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 的模式基本相同,只是使用第一个分组查询作为您要分组的 table。