Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Group and total, but return all rows in each group

Tags:

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.

like image 922
MJ Bonanno Avatar asked Jan 26 '15 20:01

MJ Bonanno


People also ask

How do you get a record with maximum value for each group?

MySQL MAX() function with GROUP BY retrieves maximum value of an expression which has undergone a grouping operation (usually based upon one column or a list of comma-separated columns).

How do I sum after GROUP BY in SQL?

SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group. It is better to identify each summary row by including the GROUP BY clause in the query resulst.

Which group is used to put the same value in all the rows?

Summary. The GROUP BY Clause SQL is used to group rows with same values. The GROUP BY Clause is used together with the SQL SELECT statement.

How do I count rows in MySQL by group?

In MySQL, the COUNT() function calculates the number of results from a table when executing a SELECT statement. It does not contain NULL values. The function returns a BIGINT value. It can count all the matched rows or only rows that match the specified conditions.


2 Answers

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.

like image 112
Barmar Avatar answered Oct 08 '22 22:10

Barmar


SELECT member_id, amount
FROM sold_items si
INNER JOIN (SELECT member_id, 
SUM(amount) AS total 
FROM `sold_items` 
GROUP BY member_id 
HAVING total > 50) spenders USING (member_id)

The query you have already built can be used as a temporary table to join with. if member_id is not an index on the table, this will become slow with scale. The word spenders is a table alias, you can use any valid alias in its stead.

like image 30
kishkash Avatar answered Oct 08 '22 20:10

kishkash