tags:

views:

305

answers:

2

Right, another question on queries (there must be a syntax guide more helpful than mySQL's manual, surely?)

I have this query (from another helpful answer on SO)...

SELECT DATE_FORMAT(`when`, '%e_%c_%Y')date, COUNT(`ip`) AddressCount FROM `Metrics` WHERE `ID` = '1' GROUP BY DATE(`when`)

I now want to do a similar query to get unique/distinct results for the IPs... i.e. unique visitors per date. My query was this...

SELECT DATE_FORMAT(`when`, '%e_%c_%Y')date, COUNT(distinct `ip`) AddressCount FROM `Metrics` WHERE `ID` = '1' GROUP BY DATE(`when`)

However, that returns a repetition of dates, though different quantities of Addresscount...

date    AddressCount
29_6_2009   1
30_6_2009   1
29_6_2009   1
30_6_2009   1
29_6_2009   1
NULL    1
15_5_2009   1
14_5_2009   2
NULL    3
14_5_2009   4
15_5_2009   1
26_6_2009   1
29_6_2009   1
26_6_2009   1
15_5_2009   1
26_6_2009   1
29_6_2009   1

Any ideas on where I'm going wrong?

+1  A: 

Your group by will need to match the data you're selecting, so this should work:

SELECT DATE_FORMAT(`when`, '%e_%c_%Y')date, COUNT(distinct `ip`) AddressCount FROM `Metrics` WHERE `ID` = '1' GROUP BY date
Whisk
Hello Whisk. I did actually try that as well, but though it seems to return a correct result, in only returns one result for one date the 29/06/09 it returns 7.
WiseDonkey
Sorry, I'm not quite sure what you mean - it returns results, but when you check them against the data it's incorrect?
Whisk
I mean that the I get a single result, a correct result.... but only a single result. For the 29/06/09 it returns 7.
WiseDonkey
Contrary to popular belief, this now works. I can't see any different formatting from what you originally said so it must be my typo's at last check out. Many thanks.
WiseDonkey
A: 

Try

SELECT DATE_FORMAT(when, '%e_%c_%Y')date, COUNT(distinct ip) AddressCount FROM Metrics WHERE ID = '1' GROUP BY date(when)

You might have run into some bugs when using reserved words in MySQL

Jonathan
when is a reserverd word so it has to be back ticked... with backticks on that query it returns my original problem result :/Thanks for looking, any other ideas?
WiseDonkey