mysql 分组返回,MySQL-分组和总计,但返回每个分组中的所有行

I'm trying to write a query that finds each time the same person occurs in my table between a specific date range. It then groups this person and totals their spending for a specific range. If their spending habits are greater than X amount, then return each and every row for this person between date range specified. Not just the grouped total amount. This is what I have so far:

SELECT member_id,

SUM(amount) AS total

FROM `sold_items`

GROUP BY member_id

HAVING total > 50

This is retrieving the correct total and returning members spending over $50, but not each and every row. Just the total for each member and their grand total. I'm currently querying the whole table, I didn't add in the date ranges yet.

解决方案

JOIN this subquery with the original table:

SELECT si1.*

FROM sold_items AS si1

JOIN (SELECT member_id

FROM sold_items

GROUP BY member_id

HAVING SUM(amount) > 50) AS si2

ON si1.member_id = si2.member_id

The general rule is that the subquery groups by the same column(s) that it's selecting, and then you join that with the original query using the same columns.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值