mysql - 聚合函数无法按预期使用子查询

标签 mysql subquery sum aggregate max

通过提出困难的问题来获得 MySQL 的乐趣。

基本上我有一个充满交易的表格,我想从中确定所有可用产品 (productid),谁 (userid) 购买了大多数? where子句中的type为交易类型,1为购买。

我有一个子查询,它自己返回为每个人购买的总计产品列表,它本身运行良好。然后我试图从中选择总和数量的最大值并按产品分组,这是一个非常简单的聚合。不幸的是,它给了我有趣的结果! userid 与报告的最大 productid 销售额不正确对应。

select 
    `userid`, `productid`, max(`sumqty`)
from
    (select 
        `userid`, `productid`, sum(`qty`) as `sumqty`
    from
        `txarchive`
    where
        `type` = 1
    group by `userid`,`productid`) as `t1`
group by `productid`

我删除了所有内部连接以提供更多口头结果,因为它们不会改变所有逻辑。

如果你有兴趣,这里是tx的结构。

id          bigint(20)    #transaction id
UserID      bigint(20)    #user id, links to another table.
ProductID   bigint(20)    #product id, links to another table.
DTG         datetime      #date and time of transaction
Price       decimal(19,4) #price per unit for this transaction
QTY         int(11)       #QTY of products for this transaction
Type        int(11)       #transaction type, from purchase to payment etc.
info        bigint(20)    #information string id, links to another table.

*编辑 工作最终查询:(它很大)

select 
    `username`, `productname`, max(`sumqty`)
from
    (select 
        concat(`users`.`firstname`, ' ', `users`.`lastname`) as `username`,
            `products`.`name` as `productname`,
            sum(`txarchive`.`qty`) as `sumqty`
    from
        `txarchive`
    inner join `users` ON `txarchive`.`userid` = `users`.`id`
    inner join `products` ON `txarchive`.`productid` = `products`.`id`
    where
        `type` = 1
    group by `productname`,`username`
    order by `productname`,`sumqty` DESC) as `t1`
group by `productname`
order by `sumqty` desc

最佳答案

不是最好的解决方案(甚至不能保证 100% 的时间都有效):

select 
    `userid`, `productid`, max(`sumqty`)
from
    ( select 
          `userid`, `productid`, sum(`qty`) as `sumqty`
      from
          `txarchive`
      where
          `type` = 1
      group by 
          `productid`  
        , `userid`
      order by 
          `productid`
        , `sumqty` DESC          
    ) as `t1`
group by
    `productid`

关于mysql - 聚合函数无法按预期使用子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8571547/

相关文章:

mysql - 复制具有公共(public)列的表数据

php - 如何将以特定名称开头的 2 个帖子(已提交)值插入到同一表行,并循环以获得更多相同的结果?

mysql - 一次 2 个 mysql 查询

mysql - 如何在 MySQL 中对行求和

python - 从多列python中查找

mysql - Cakephp 虚拟字段如果此列为空则使用此列

php - 使用主键引用行进行更新

mysql - 用join代替子查询有意义吗?

mysql - 来自子查询的两列(mysql)

mysql - 如何正确总结为 “Order Time” + “leave Time” - mysql (添加小时而不是秒)