mysql - 选择具有最大字段数的记录

标签 mysql sql

查询 1:

SELECT MaxTable.Customer,
       MaxTable.Product,
       Count(MaxTable.Product) AS CountOfProduct
FROM MaxTable
GROUP BY MaxTable.Customer, MaxTable.Product 

这将创建一个派生表,我想将其命名为 Product_count_query

查询 2:

SELECT Product_count_query.Customer,
       Max(Product_count_query.CountOfProduct) AS MaxOfCountOfProduct
FROM Product_count_query
GROUP BY Product_count_query.Customer;

这将创建一个派生表,我想将其命名为 max_customer_count

查询 3:

SELECT Product_count_query.Customer,
       Product_count_query.Product,
       Product_count_query.CountOfProduct
FROM Max_Customer_Count
INNER JOIN Product_count_query ON 
       (Max_Customer_Count.MaxOfCountOfProduct = Product_count_query.CountOfProduct) AND
       (Max_Customer_Count.Customer = Product_count_query.Customer);

我想将这三个查询合二为一以获得这样的结果

Customer Name   Products with max number

我的示例表是

Customer Product
James Keyboard
James Monitor
James Keyboard

输出表是(如果 James 买了 2 个键盘和 1 个显示器)

Customer Product Countof 产品 詹姆斯键盘 2

如果购买的产品数量相同,则应使用逗号分隔符连接产品名称和产品数量。

最佳答案

很遗憾 Mysql 不支持 ROW_NUMBER 窗口函数,所以,

试试这个

SELECT Customer,
       Group_concat(Product separator ','),
       Group_concat(CountOfProduct separator ',')
FROM   (SELECT MaxTable.Customer,
               MaxTable.Product,
               Count(MaxTable.Product) AS CountOfProduct
        FROM   MaxTable
        GROUP  BY MaxTable.Customer,
                  MaxTable.Product) a
WHERE  CountOfProduct = (SELECT Max(CountOfProduct)
                         FROM   (SELECT MaxTable.Customer,
                                        MaxTable.Product,
                                        Count(MaxTable.Product) AS CountOfProduct
                                 FROM   MaxTable
                                 GROUP  BY MaxTable.Customer,
                                           MaxTable.Product) b
                         WHERE  a.Customer = b.Customer)
GROUP  BY Customer

使用GROUP_CONCAT当有平局时连接结果

关于mysql - 选择具有最大字段数的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36243630/

相关文章:

sql - 如何引用名称中带有空格的列?

sql - 使用 IN 关键字查询

MySQL - 根据时间戳查找 bin 日志位置

mysql - 在mysql中连接字符串并在它们之间添加字符

php - 不同行的MySQL总和

sql - TSQL - 获取当前时间的最后一秒

c# - .net DateTime MaxValue 一旦存储在数据库中就不同了

php - 在存储在数据库中的序列化值中搜索

mysql - 更新具有 2800 万条记录的表中每条记录的列

mysql - 元数据 Excel 文件 : What would the Domain and Range be?