Reputation: 5456
I have this records in MySQL below
RecID | Description | Date | Hits | IsPublished
1; "Test"; 04/10/2012; 45; True
2; "Test 1"; 04/10/2012; 37; True
3; "Test 2"; 05/10/2012; 12; True
4; "Test 3"; 05/10/2012; 13; True
5; "Test 4"; 07/10/2012; 14; True
6; "Test 5"; 07/10/2012; 25; True
7; "Test 4"; 08/10/2012; 23; True
8; "Test 5"; 08/10/2012; 35; True
9; "Test 9"; 12/10/2012; 7; True
Would like to achieve the following
9; "Test 9"; 12/10/2012; 7; True
8; "Test 5"; 08/10/2012; 35; True
4; "Test 3"; 05/10/2012; 13; True
Basically, the first rule is to group the date which is 08/10/2012, 07/10/2012 and 05/10/2012 and 04/10/2012. Use this 08/10/2012 as a starting point. Then remove any dates that is close to each other (min 1 day).
BTW ... this is an Australian date (DD/MM/YYYY). Therefore, the result is 08/10/2012, 05/10/2012. Out of these 2 "valid" days and then pick the record that has more hits on that day. Then set the others as IsPublished = false.
Any ideas to do this in MySQL?
Upvotes: 0
Views: 182
Reputation: 35531
First find the dates that have no other rows with a day larger by 1:
SELECT DISTINCT t1.Date
FROM table_name t1
LEFT JOIN table_name t2
ON DATE_ADD(t1.Date, INTERVAL 1 DAY) = t2.Date
WHERE t2.RecId IS NULL
Then find the max hits for these dates:
SELECT Date, MAX(Hits) as maxHits
FROM table_name
WHERE Date IN (
SELECT DISTINCT t1.Date
FROM table_name t1
LEFT JOIN table_name t2
ON DATE_ADD(t1.Date, INTERVAL 1 DAY) = t2.Date
WHERE t2.RecId IS NULL )
GROUP BY Date
Finally, update all rows that don't match these dates and maxHits:
UPDATE table_name toUpdate, (
SELECT Date, MAX(Hits) as maxHits
FROM table_name
WHERE Date IN (
SELECT DISTINCT t1.Date
FROM table_name t1
LEFT JOIN table_name t2
ON DATE_ADD(t1.Date, INTERVAL 1 DAY) = t2.Date
WHERE t2.RecId IS NULL )
GROUP BY Date) source
SET toUpdate.IsPublished = false
WHERE toUpdate.Date != source.Date OR toUpdate.Hits != source.maxHits
Upvotes: 1