通过提出困难的问题来获得 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/