计算给定日期范围内每个月的平均值

时间:2019-01-30 10:47:32

标签: mysql sql date group-by aggregate-functions

我有一个 employees 表,其中每个雇员都有一个相关的开始日期结束日期和一个薪金。 / p>

注意::在底部,您可以找到用于导入结构和数据的SQL代码。

+----+-------+------------+------------+---------+
| id | name  | start_date | end_date   | salary  |
+----+-------+------------+------------+---------+
|  1 | Mark  | 2017-05-01 | 2020-01-31 | 2000.00 |
|  2 | Tania | 2018-02-01 | 2019-08-31 | 5000.00 |
|  3 | Leo   | 2018-02-01 | 2018-09-30 | 3000.00 |
|  4 | Elsa  | 2018-12-01 | 2020-05-31 | 4000.00 |
+----+-------+------------+------------+---------+

问题

对于给定的日期范围,我想提取给定日期范围内每个月的平均工资。

更新:我想拥有MySQL 5.6的解决方案,但是也有适用于MySQL 8+的解决方案(仅出于个人知识)将非常棒。

示例

如果日期范围为 2018-08-01 - 2019-01-31 ,则SQL报表应在2018年8月至2019年1月之间循环,并且必须计算每个月的平均工资:

  • 2018年8月中,在职员工是 Mark Tania Leo (因为2018年8月在他们之间开始日期结束日期),因此平均值为 3333.33
  • 2018年9月,在职员工是 Mark Tania Leo (因为2018年9月在他们之间开始日期结束日期),因此平均值为 3333.33
  • 2018年10月中,在职员工是 Mark Tania ,因此平均水平为 3500.00
  • 2018年11月中,在职员工是 Mark Tania ,因此平均值为 3500.00
  • 2018年12月中,在职员工是 Mark Tania Elsa ,因此平均值为 3666.6667
  • 2019年1月的在职员工是 Mark Tania Elsa ,因此平均值为 3666.6667

下面您将看到日期范围 2018-08-01 - 2019-01-31 < / strong>

+------+-------+------------+
| year | month | avg_salary |
+------+-------+------------+
| 2018 | 08    | 3333.33    |
| 2018 | 09    | 3333.33    |
| 2018 | 10    | 3500.00    |
| 2018 | 11    | 3500.00    |
| 2018 | 12    | 3666.67    |
| 2019 | 01    | 3666.67    |
+------+-------+------------+

注意:我解决了将MySQL与PHP代码混合使用的问题,但在较大的日期范围内,它必须执行过多的查询(每个月执行一次)。因此,我想有一个仅使用MySQL 的解决方案。

SQL导入结构和数据

CREATE TABLE `employees` (
  `id` int(10) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL,
  `salary` decimal(10,2) DEFAULT NULL
);

INSERT INTO `employees` (`id`, `name`, `start_date`, `end_date`, `salary`) VALUES
(1, 'Mark', '2017-05-01', '2020-01-31', '2000.00'),
(2, 'Tania', '2018-02-01', '2019-08-31', '5000.00'),
(3, 'Leo', '2018-02-01', '2018-09-30', '3000.00'),
(4, 'Elsa', '2018-12-01', '2020-05-31', '4000.00');

5 个答案:

答案 0 :(得分:3)

这是MySQL 8.0递归CTE的实现方式。 CTE在year, month表中的最小start_date和最大end_date之间创建所有employees组合的列表,然后将其LEFT JOIN固定到{ {1}}表以获取该特定年份和月份中所有在职员工的平均工资:

employees

输出:

WITH RECURSIVE months (year, month) AS
(
  SELECT YEAR(MIN(start_date)) AS year, MONTH(MIN(start_date)) AS month FROM employees
  UNION ALL
  SELECT year + (month = 12), (month % 12) + 1 FROM months
  WHERE STR_TO_DATE(CONCAT_WS('-', year, month, '01'), '%Y-%m-%d') <= (SELECT MAX(end_date) FROM employees)
)
SELECT m.year, m.month, ROUND(AVG(e.salary), 2) AS avg_salary
FROM months m
LEFT JOIN employees e ON STR_TO_DATE(CONCAT_WS('-', m.year, m.month, '01'), '%Y-%m-%d') BETWEEN e.start_date AND e.end_date
WHERE STR_TO_DATE(CONCAT_WS('-', m.year, m.month, '01'), '%Y-%m-%d') BETWEEN '2018-08-01' AND '2019-01-31'
GROUP BY m.year, m.month

Demo on dbfiddle

答案 1 :(得分:2)

您只需键入所需的月份(或使用PHP代码生成它们)并加入:

SELECT ym, AVG(salary)
FROM (
    SELECT '2018-08-01' + INTERVAL 0 MONTH AS ym UNION ALL
    SELECT '2018-08-01' + INTERVAL 1 MONTH UNION ALL
    SELECT '2018-08-01' + INTERVAL 2 MONTH UNION ALL
    SELECT '2018-08-01' + INTERVAL 3 MONTH UNION ALL
    SELECT '2018-08-01' + INTERVAL 4 MONTH UNION ALL
    SELECT '2018-08-01' + INTERVAL 5 MONTH
) AS yearmonths
JOIN employees ON ym BETWEEN start_date AND end_date
GROUP BY ym

如果您的表包含数字0、1 ...,则可以使用该表。您甚至可以使用具有足够行数的 任何 表:

SELECT ym, AVG(salary)
FROM (
    SELECT '2018-08-01' + INTERVAL @n := @n + 1 MONTH AS ym
    FROM anytable, (SELECT @n := -1) x
    LIMIT 100
) AS yearmonths
JOIN employees ON ym BETWEEN start_date AND end_date
WHERE ym <= '2019-01-01'
GROUP BY ym

答案 2 :(得分:1)

要完成此操作,您需要从日期范围生成天列表。这是一个关于SO的常见问题,我使用了this post中公认的解决方案。它使用一种简单的算术方法,并且可以生成日期的广泛列表(尽管性能可能会受到影响)。

然后,我们只需要与原始表进行联接,以计算该时间点的平均工资。

select
  year(x.date), 
  month(x.date),
  avg(coalesce(e.salary, 0)) avg_salary
from (
  select a.date 
  from (
      select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a) + (1000 * d.a) ) DAY as Date
      from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
      cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
      cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
      cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as d
  ) a
  where a.date between '2018-08-01' and '2019-01-31'
) x left join employees e ON x.date between e.start_date and e.end_date
group by year(x.date), month(x.date)
order by 1, 2

Demo on DB fiddle

| year(x.date) | month(x.date) | avg_salary  |
| ------------ | ------------- | ----------- |
| 2018         | 8             | 3333.333333 |
| 2018         | 9             | 3333.333333 |
| 2018         | 10            | 3500        |
| 2018         | 11            | 3500        |
| 2018         | 12            | 3666.666667 |
| 2019         | 1             | 3666.666667 |

PS:另一种方法是创建一个日历表,该表存储天数列表,然后只是:

select
  year(x.date), 
  month(x.date),
  avg(coalesce(e.salary, 0)) avg_salary
from 
  mycalendar x
  left join employees e ON x.date between e.start_date and e.end_date
where x.date between '2018-08-01' and '2019-01-31'
group by year(x.date), month(x.date)
order by 1, 2

答案 3 :(得分:0)

部分答案...

这是一个使用整数(0-9)表的“老派”解决方案,但请注意,这种情况在较新版本的sql中是多余的...

SELECT * FROM ints;
  +---+
  | i |
  +---+
  | 0 |
  | 1 |
  | 2 |
  | 3 |
  | 4 |
  | 5 |
  | 6 |
  | 7 |
  | 8 |
  | 9 |
  +---+

SELECT '2018-08-01' + INTERVAL i2.i * 10 + i1.i MONTH x 
  FROM ints i1
     , ints i2 
 WHERE '2018-08-01' + INTERVAL i2.i * 10 + i1.i MONTH BETWEEN '2018-08-01' AND '2019-01-31';

  +------------+
  | x          |
  +------------+
  | 2018-08-01 |
  | 2018-09-01 |
  | 2018-10-01 |
  | 2018-11-01 |
  | 2018-12-01 |
  | 2019-01-01 |
  +------------+

答案 4 :(得分:-1)

以下是执行此操作的Postgresql方法。可以通过更改Mysql中的generate_series() linkExtract()的等效项将其转换为Mysql查询

WITH cte1 AS
  (SELECT generate_series('2018-08-01', '2019-01-31', '1 month'::interval)::date AS date),
     cte2 AS
  (SELECT id,
          name,
          salary,
          generate_series(start_date, end_date, '1 month'::interval)::date AS date
   FROM employees)
SELECT extract(YEAR
               FROM cte1.date),
       extract(MONTH
               FROM cte1.date),
       avg(salary)
FROM cte1
JOIN cte2 ON extract(MONTH
                     FROM cte1.date)=extract(MONTH
                                             FROM cte2.date)
AND extract(YEAR
            FROM cte1.date)=extract(YEAR
                                    FROM cte2.date)
GROUP BY extract(YEAR
                 FROM cte1.date),
         extract(MONTH
                 FROM cte1.date);