Skip to content

Instantly share code, notes, and snippets.

@ryuichimatsumoto-single
Created December 23, 2016 08:45
Show Gist options
  • Save ryuichimatsumoto-single/e9c96bece656551d20a101d62fdef46d to your computer and use it in GitHub Desktop.
Save ryuichimatsumoto-single/e9c96bece656551d20a101d62fdef46d to your computer and use it in GitHub Desktop.
1ヶ月おきの累計売上高をMySQLで集計し、Excelでグラフにする ref: http://qiita.com/ryuichi69/items/ba0858c3af977adff418
CREATE TABLE IF NOT EXISTS `tbl` (
`id` int(10) NOT NULL COMMENT '主キー',
`time` datetime NOT NULL COMMENT '集計日',
`sales` int(100) NOT NULL COMMENT 'その日の売上高'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `tbl` (`id`, `time`, `sales`)
VALUES
(NULL, '2016-01-04 12:00:00', '1000000'),
(NULL, '2016-02-10 13:00:00', '1400000'),
(NULL, '2016-02-25 15:00:00', '600000'),
(NULL, '2016-03-04 16:00:00', '800000'),
(NULL, '2016-03-25 18:00:00', '800000'),
(NULL, '2016-04-20 09:00:00', '500000'),
(NULL, '2016-04-29 14:00:00', '400000'),
(NULL, '2016-05-11 00:00:00', '700000'),
(NULL, '2016-05-30 15:00:00', '300000'),
(NULL, '2016-06-22 17:00:00', '1200000');
SELECT
date_format(a.time,'%Y-%m') as dt,
sum(a.sales),
(
SELECT
sum(b.sales)
FROM
tbl b
WHERE
date_format(b.time, '%Y-%m') <= date_format(a.time,'%Y-%m')
and
date_format(b.time,'%Y-%m') >= '2016-01'
)
as total
from
tbl a
where
a.time between '2016-01-01 00:00:00' and '2016-12-31 23:59:59'
group by dt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment