简体   繁体   English

如何在 MYSQL 中使用 COUNT 和 GROUP BY 同时仍显示所有单独的行?

[英]How can I use COUNT and GROUP BY in MYSQL while still displaying all individual rows?

I am just trying some practise exercises with MYSQL.我只是在尝试使用 MYSQL 进行一些练习。 I have a dataset where I would like to get the names of customers who ordered two or more different kinds of item and how many of each kind of item they bought.我有一个数据集,我想在其中获取订购两种或多种不同商品的客户的姓名以及他们购买了每种商品的数量。

The query below gives me a row for each name of the purchaser.下面的查询为购买者的每个姓名提供了一行。 However, I also want to display what types of items they bought and how many of them.但是,我还想显示他们购买了哪些类型的商品以及购买了多少。 Ideally I would like to have the same number of rows for each customer for how many different items they bought.理想情况下,我希望每个客户购买了多少不同商品的行数相同。

SELECT firstname, familyname, description, quantity
FROM customers c
JOIN orders o ON o.custID = c.custID
JOIN lineitems l on o.orderID = l.orderID
JOIN items i on l.itemID = i.itemID
GROUP BY firstname
HAVING count(description) 

The query below does give me a row for each item, how many items that person bought, and the name of the purchaser.下面的查询确实为每件商品提供了一行,该人购买了多少商品以及购买者的姓名。 However, it does not filter for customers who only bought one specific item anymore.但是,它不再过滤仅购买一件特定商品的客户。

SELECT firstname, familyname, description, quantity
FROM customers c
JOIN orders o ON o.custID = c.custID
JOIN lineitems l on o.orderID = l.orderID
JOIN items i on l.itemID = i.itemID
WHERE EXISTS(
    SELECT *
    FROM customers
    GROUP BY firstname
    HAVING count(description) >= 2)

Basically I would like to combine both approaches where there are multiple rows for specific item for each customer, while also filtering out customers who only bought one type of item.基本上我想结合这两种方法,其中每个客户的特定商品有多行,同时也过滤掉只购买一种商品的客户。

If you are running MySQL 8.0, you can do a window count in a subquery and filter in the outer query, like:如果您正在运行 MySQL 8.0,您可以在子查询中执行 window 计数并在外部查询中进行过滤,例如:

SELECT *
FROM (
    SELECT 
        c.firstname, 
        c.familyname, 
        i.description, 
        l.quantity, 
        COUNT(*) OVER(PARTITION BY c.custID) cnt
    FROM customers c
    JOIN orders o ON o.custID = c.custID
    JOIN lineitems l on o.orderID = l.orderID
    JOIN items i on l.itemID = i.itemID
) x
WHERE cnt > 1

Note: it is a good practice to prefix column names with the alias of the table they belong to;注意:最好在列名前加上它们所属表的别名; this makes the query more readable and avoid clashes when the same column name exists across tables.这使得查询更具可读性并避免跨表存在相同列名时发生冲突。 I made a few assumptions and updated the query accordingly.我做了一些假设并相应地更新了查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM