MySQL在同一列上使用带有GROUP BY的DISTINCT

时间:2016-06-20 04:58:13

标签: mysql

我目前的查询类似于:

distinct

查询的目的是将客户与他们购买的商品相关联,这些商品可能会跨越多个订单,并且总计购买的每件商品的总金额。这是通过我所拥有的来实现的。我现在想更进一步,为每个客户选择最受欢迎的项目。由于这是订购时最常购买的商品,我想我只需要在customers.customerId语句的select旁边添加distinct即可删除重复项。但是,添加distinct似乎无能为力。我很高兴知道为什么customers customerId | name 1 | John 2 | Jane orders orderId | customerId | quantity | itemId 1 | 1 | 11 | 1 2 | 2 | 13 | 2 3 | 1 | 4 | 2 4 | 2 | 14 | 1 5 | 1 | 1 | 1 items itemId | itemName 1 | dog 2 | cat 似乎在这里什么也不做,以及如何实现我想要做的事情 - 除了客户最受欢迎的项目之外,还要删除重复项。< / p>

表:

 customerId | itemName | boughtTotal
      2     |    dog   |     14
      2     |    cat   |     13
      1     |    dog   |     12
      1     |    cat   |     4

因此,从这些数据中,当前查询将返回以下内容:

 customerId | itemName | boughtTotal
      2     |    dog   |     14
      1     |    dog   |     12

我想要的是以下内容:

{{1}}

1 个答案:

答案 0 :(得分:1)

试试这个;)

select t1.*
from (
    select customers.customerId, items.itemName, sum(orders.quantity) as boughtTotal 
    from customers join orders on customers.customerId = orders.customerId 
    join items on items.itemId = orders.itemId
    group by customers.customerId, items.itemName) t1
inner join (
    select max(boughtTotal) as boughtTotal, customerId
    from (
        select customers.customerId, items.itemName, sum(orders.quantity) as boughtTotal 
        from customers join orders on customers.customerId = orders.customerId 
        join items on items.itemId = orders.itemId
        group by customers.customerId, items.itemName)t
    group by customerId) t2 on t1.customerId = t2.customerId and t1.boughtTotal = t2.boughtTotal 

DEMO HERE