通过询问难题来获得MySQL的乐趣。
基本上我有一个充满交易的表格,从中我想确定所有可用的产品(productid
),谁(userid
)已经购买了大部分产品? where子句中的类型是指交易类型,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
答案 0 :(得分:1)
不是最好的解决方案(甚至不保证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`