I am working on a project where I need to get the minimum and maximum date from a database as well substringing the first part of a field up to a character and grouping by this field. So basically in the database I have
2012-01-01 Unknown username/password attempted to login. User: admin
2012-01-01 Failed to add user account. MySQL Error: certain my sql
error Unknown2012-01-02 Failed to add user account. MySQL Error: certain my sql
error Unknown2012-01-04 Unknown username/password attempted to login. User:
administrator
Below is the query that I am using which is working without showing the date
SELECT ala_type, partMsg,
wholeMsg, ala_level, ala_page, COUNT(wholeMsg) AS msgCount FROM
(
SELECT ala_type, SUBSTRING_INDEX(ala_message, ':', 1) AS partMsg, ala_message AS wholeMsg,
ala_level, ala_page FROM alarms a) p
GROUP BY partMsg
This bit is grouping correctly as expected but if I try to add a min(date_field) it then only shows one record.
Below is the query that I have tried
SELECT ala_date, min(ala_date), max(ala_date), ala_type, partMsg,
wholeMsg, ala_level, ala_page, COUNT(wholeMsg) AS msgCount FROM (
SELECT ala_date, min(ala_date), max(ala_date), ala_type,
SUBSTRING_INDEX(ala_message, ‘:’, 1) AS partMsg, ala_message AS
wholeMsg, ala_level, ala_page FROM alarms a) p GROUP BY partMsg
If I don’t put ala_date in the second statement and just have min(ala_date) it says that it can’t find the field ala_date. However, when I run the query I am only getting one record and I would have expected to see the following
2012-01-01 2012-01-04 Unknown username/password attempted to login.User: 2
2012-01-01 2012-01-02 Failed to add user account. MySQL Error: > certain mysql error 2
The 2 and the end of the expected result is the count how many times the message occurred.
What I am actually getting is:
2012-01-01 2012-01-01 2012-01-01 Failed to add user account… 1
It is now only showing 1 record and the min and max only are the same and the count is 1 instead of 2.
What could I do to get what I am expecting to get.
Thanks for any help you can provide.
You would do something like (my mysql is rusty) but the theoiry is sound.
ie find the minimum date for for each group then join back to the original table to find the records that were also on that date.