建立查询“按月平均金额”,填补上个月的差距

时间:2014-09-22 17:54:16

标签: mysql sql

我有问题。我需要构建报表查询以按月计算平均金额。 如果帐户中的用户在本月没有购买任何商品,我应该使用上个月的amount

这是我的数据:您可以看到我在7月(2014-07)有一个帐户操作,8月(2014-08)有一个操作。

CREATE TABLE IF NOT EXISTS `value_hist` (
  `id` int(11) NOT NULL,
  `account_id` int(11) DEFAULT NULL,
  `data_channel_id` int(11) DEFAULT NULL,
  `status` tinyint(1) NOT NULL,
  `amount` decimal(19,4) NOT NULL COMMENT '(DC2Type:money)(DC2Type:money)',
  `created_at` datetime NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=8 ;

INSERT INTO `value_hist` (`id`, `account_id`, `data_channel_id`, `status`, `amount`, `created_at`)
VALUES
 (28, 19, 2, 0, 100.0000, '2014-08-22 14:59:47'),
 (29, 19, 2, 0, 11.0000,  '2014-09-22 15:05:36'),
 (30, 19, 2, 0, 22.0000,  '2014-09-22 15:10:59'),
 (31, 19, 2, 0, 0.0000,   '2014-09-22 15:14:19'),
 (32, 19, 2, 0, 22.0000,  '2014-09-22 15:15:58'),
 (33, 19, 2, 0, 0.0000,   '2014-09-22 15:17:29'),
 (34, 1, 2, 0, 50.0000,   '2014-07-22 15:20:10'),
 (35, 1, 2, 0, 0.0000,    '2014-09-22 15:23:37'),
 (36, 1, 2, 0, 100.0000,  '2014-09-22 15:23:39'),
 (37, 1, 2, 1, 0.0000,    '2014-09-22 15:30:53'),
 (38, 19, 2, 0, 100.0000, '2014-09-22 15:30:53'),
 (39, 28, 2, 1, 0.0000,   '2014-09-22 15:36:44'),
 (40, 19, 2, 1, 0.0000,   '2014-09-22 15:45:24'),
 (41, 6, 2, 0, 0.0000,    '2014-09-22 15:48:54'),
 (42, 6, 2, 0, 200.0000,  '2014-09-22 15:49:34'),
 (43, 6, 2, 1, 33.0000,   '2014-09-22 15:50:18');

我已经构建了一个查询。哪个可以从每个月获得平均值

SELECT 
    data_channel_id,
    test2.monthaa,
    AVG(h1.amount) as amount
FROM
    value_hist h1
    JOIN (
     SELECT  MAX(dd.`id`) as id, EXTRACT(month from dd.created_at) as monthaa
     FROM value_hist dd 
     where dd.created_at > '01.01.2014' 
     GROUP BY  data_channel_id,  dd.account_id, monthaa
    ) test2 ON test2.id =  h1.id
WHERE
    created_at > '01.01.2014'
GROUP BY data_channel_id, monthaa

每个月的结果返回平均值

| channel | month | amount |
| 2       | 7     | 50.0000|
| 2       | 8     | 100.000|
| 2       | 9     | 8.25000|

但我应该得到这个结果,我应该考虑上个月amount。例如(100 + 50)/ 2,因为帐户1在8月(2014-08)没有购买

| channel | month | amount |
| 2       | 7     | 50.0000|
| 2       | 8     | 75.0000|
| 2       | 9     | 8.25000|

更新:7月份只有一个帐户(7)因此等于50.00; (50.00 / 1 = 50.00)。 8月(8)因此,第二个账户的金额等于75.00; ((100.00 + 50)/ 2 = 75.00)因为我在八月(8)有两个帐户。

0 个答案:

没有答案