Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL get unique month year combos

SELECT     MONTH(sessionStart) AS Expr1, YEAR(sessionStart) AS Expr2
FROM         tblStatSessions
WHERE     (projectID = 187)
GROUP BY sessionStart

This returns:

11 | 2010

11 | 2010

11 | 2010

12 | 2010

12 | 2010

But I need it to only return each instance once, IE:

11 | 2010

12 | 2010

If that makes sense!

like image 858
Tom Gullen Avatar asked Jan 04 '11 12:01

Tom Gullen


1 Answers

The following should be what you want:

SELECT     MONTH(sessionStart) AS Expr1, YEAR(sessionStart) AS Expr2
FROM         tblStatSessions
WHERE     (projectID = 187)
GROUP BY MONTH(sessionStart), YEAR(sessionStart)

in general you need to group by every non-aggregate column that you are selecting. Some DBMSs, such as Oracle, enforce this, i.e. not doing so results in an error rather than 'strange' query execution.

like image 120
John Pickup Avatar answered Oct 25 '22 13:10

John Pickup