Thursday, December 17, 2015

MySql prepare historic data for reporting purpose

-- Prepare a table for days to get sequence of numbers from 1 to 32

CREATE TABLE ids (
id INT UNSIGNED AUTO_INCREMENT NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM;

INSERT INTO ids SET id = 1;           #      1      1
INSERT INTO ids SELECT NULL FROM ids; #      2      2
INSERT INTO ids SELECT NULL FROM ids; #      4      4
INSERT INTO ids SELECT NULL FROM ids; #      8      8
INSERT INTO ids SELECT NULL FROM ids; #     10     16
INSERT INTO ids SELECT NULL FROM ids; #     20     32


set @enddate = "2015-12-01";
set @days = 15;

SELECT date(qb.date) as date, COALESCE(sum(net_amount), 0) as total from invoice qa
right join
(SELECT
(SELECT @enddate FROM invoice qc LIMIT 1) + INTERVAL 1 DAY - INTERVAL a.id DAY AS date
FROM test.ids a
    ) as qb
on date(qa.date) = qb.date
where qb.date > DATE_SUB(@enddate, INTERVAL @days day)
group by qb.date
order by qb.date asc;

No comments:

Post a Comment