选择具有最大字段数

时间:2016-03-27 03:49:44

标签: mysql sql

QUERY 1:

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

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

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

QUERY 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

输出表将是(如果詹姆斯购买了2个键盘和1个显示器)

客户产品数量产品     詹姆斯键盘2

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

1 个答案:

答案 0 :(得分:1)

遗憾的是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在存在平局时连接结果