MorkaLork Development

Interesting stuff I've picked up over the years...

Mysql 10: GROUP BY

2009-04-16 21:18:08 | 151 views | sql mysql table group by sum function together records

GROUP BY:



If you're using the SUM function(mentioned in the Functions-article) you might want to sort equal records together. If we have several stores and we want to sum up each stores sales, we need to group all store records together.


This will be our table 'stores'

|--------------------+--------------------+--------------------|
|store_name |store_sales |store_updates |
|____________________+____________________+____________________|
|Hanks Hardware 2500 2009-01-01 00:00:00 |
|Santos SuperStore 750 2008-12-01 00:00:00 |
|Bobs Boutique 1250 2009-01-01 00:00:00 |
|Pattyïs Pantstore 1050 2008-12-15 00:00:00 |
|Hanks Hardware 2250 2008-01-01 00:00:00 |
+--------------------------------------------------------------+


Now, Hanks Hardware store has two records, one for each year. If we want to use SUM here, we want those two records to be regarded as one store, since it is the same one.

Syntax:

SELECT column, SUM(column)
FROM table_name
GROUP BY column


Example:


|--------------------+--------------------|
|store_name |SUM(store_sales) |
|____________________+____________________|
|Bobs Boutique 1250 |
|Hanks Hardware 4750 |
|Pattyïs Pantstore 1050 |
|Santos SuperStore 750 |
+------------------------------------------+







Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.