mysql:从多个表、子查询排序?

wtzytmuj  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(373)

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

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

我想要一个查询,找出每个州和每个州最流行的项目。其中一个棘手的部分是某些产品名有多个产品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

任何帮助都将不胜感激。
谢谢您!

k5hmc34c

k5hmc34c1#

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

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列上具有最大值的行的模式相同,只是将第一个分组的查询用作要分组的表。

相关问题