Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to group by month part of timestamp

I'm really bad at SQL queries but I'm learning so please forgive this question.

Here is my current query:

SELECT TIMESTAMP, SUM( electricity ) AS electricity,  `siteID` 
FROM table
WHERE (
MONTH(  `TimeStamp` ) =10)
GROUP BY siteID

My table looks like:

#########################################
# Id # SiteID # TimeStamp  # Elecricity #
# 0  # 100    # 10/08/2012 # 50         #
# 1  # 98     # 10/08/2012 # 32         #
# 2  # 100    # 10/09/2012 # 96         #
# 3  # 94     # 10/09/2012 # 25         #
# 4  # 100    # 10/10/2012 # 100        #
# 5  # 100    # 10/11/2012 # 55         #
#########################################

What I am trying to do is to sum up all of the days of each month of each site, so that I will have one answer per site and month. So in this example the query should return the sum of the electricity values for siteID 100 because they're all in month 10, the same for siteID 98 and 94.

Thanks

like image 968
Sam Creamer Avatar asked Aug 06 '13 18:08

Sam Creamer


People also ask

How do you get the month from a timestamp field?

Use the MONTH() function to retrieve a month from a date/datetime/timestamp column in MySQL. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a date/datetime/timestamp column.

How do I SELECT a specific record of a particular month in SQL?

To select all entries from a particular month in MySQL, use the monthname() or month() function.

Can you GROUP BY date in SQL?

To group by date part, use the GROUP BY clause and the EXTRACT() function. Pass EXTRACT() the date parts to isolate.

What is %s in SQL query?

The SQL LIKE Operator There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.


1 Answers

SELECT month('TIMESTAMP'), SUM( electricity ) AS electricity,  `siteID` 
FROM table
WHERE (
MONTH(  `TimeStamp` ) =10)
GROUP BY siteID, month('TIMESTAMP')

This will work. One thing that you have to think about is that month is not unique. Oct, 2012, in this case, is the same as Oct 2013. You might want to add another column for year.

like image 160
Brian Hoover Avatar answered Oct 06 '22 22:10

Brian Hoover