A
A
anitspam2013-04-11 02:38:28
MySQL
anitspam, 2013-04-11 02:38:28

Query grouped by month from 21st to 20th

There is a table

show create table archive_day;
+-------------+-------------------
| Table       | Create Table
+-------------+-------------------
| archive_day | CREATE TABLE `archive_day` (
  `user_id` int(11) NOT NULL,
  `archive_date` date NOT NULL,
  `user_data` double(10,3) DEFAULT NULL,
  PRIMARY KEY (`user_id`,`archive_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

From this table, you must select the amount of data grouped by month
SELECT 
    SUM(`user_data`) AS `udata`,
    DATE_FORMAT(`archive_date`, '%Y-%m') AS `archive_date_analyse`
FROM `archive_day`
WHERE 
    (`user_id` = '1') 
    AND
    (`archive_date` >= '2013-01-01') 
    AND 
    (`archive_date` <= '2013-04-30')
GROUP BY 
    `archive_date_analyse`
ORDER BY 
    `archive_date_analyse` ASC

We get it like this
+--------+----------------------+
| udata | archive_date_analyse |
+--------+----------------------+
| 79.671 | 2013-01 |
| 62.574 | 2013-02 |
| 52.220 | 2013-03 |
| 14.120 | 2013-04 |
+--------+----------------------+

Now the "concept has changed" and additionally it is necessary that the grouping be from the 21st to the 20th of the month. Such periods
2013-01-01 — 2013-01-20
2013-01-21 — 2013-02-20
2013-02-21 — 2013-03-20
2013-03-21 — 2013-04-20
2013-04-21 — 2013-04-30

The first and last periods will be constrained by the conditions in where.

Whether it is possible to make such grouping by means of sql? Or is it easier to select all the data, and then process them properly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Moseev, 2013-04-11
@anitspam

the first thing that came to mind was
select MONTH(archive_date)+IF( DAY(archive_date<=20),0,1) as criteria…
where #restrict period here
group by criteria

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question