博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mysql 分组返回_MySQL-分组和总计,但返回每个分组中的所有行
阅读量:5742 次
发布时间:2019-06-18

本文共 1079 字,大约阅读时间需要 3 分钟。

bd96500e110b49cbb3cd949968f18be7.png

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.

转载地址:http://mynzx.baihongyu.com/

你可能感兴趣的文章
Windows UI风格的设计(7)
查看>>
SQL中使用WITH AS提高性能 使用公用表表达式(CTE)简化嵌套SQL
查看>>
oracle 强行杀掉一个用户连接
查看>>
Git提交本地库代码到远程服务器的操作
查看>>
让你快速上手的Glide4.x教程
查看>>
浮动和清除(闭合)浮动
查看>>
LR录制脚本时IE打不开的原因
查看>>
微博自动化测试
查看>>
Sublime Text 2.0.2,Build 2221注册码
查看>>
js scroll事件
查看>>
最长递增子序列 动态规划
查看>>
原生CSS设置网站主题色—CSS变量赋值
查看>>
webpack 4.0 中 clean-webpack-plugin 的使用
查看>>
中文词频统计
查看>>
POJ 2236 Wireless Network (并查集)
查看>>
python分类
查看>>
GitBlit (1)-- 在linux 安装 GitBlit 并运行
查看>>
程序是如何执行的(一)a=a+1
查看>>
18 已知下面的字符串是通过RANDOM随机数变量md5sum|cut-c 1-8截取后的结果
查看>>
BZOJ - 3578: GTY的人类基因组计划2
查看>>