gpt4 book ai didi

php - 用以前的值填充数组中的空白

转载 作者:行者123 更新时间:2023-11-29 12:12:39 26 4
gpt4 key购买 nike

我有一个名为 salary_raise 的表,如下所示:

id | employee_id | salary | year | month | date
1 | 1 | 1000 | 2014 | 2 | 2014-01-30
2 | 1 | 1200 | 2015 | 3 | 2015-02-20
3 | 1 | 1300 | 2015 | 4 | 2015-03-29

...对于多名员工,依此类推。仅当加薪发生时(这可能在一段时间内随机发生),它才会保留记录。

现在我可以提取一个类似于 $salary['year']['month'] = $salary_value 的数组:

[2014]
[2] => 1000
[2015]
[3] => 1200
[4] => 1300

我需要提取一份完整的报告,其中包含每个月的最新工资(自动填充缺失的月份/年份),例如:

[2014]
[2] => 1000
[3] => 1000
[4] => 1000
[5] => 1000
[6] => 1000
[7] => 1000
[8] => 1000
[9] => 1000
[10] => 1000
[11] => 1000
[12] => 1000
[2015]
[1] => 1000
[2] => 1000
[3] => 1200
[4] => 1300
[5] => 1300

我不知道如何使用 php 和/或 mysql 来做到这一点。非常感谢!

最佳答案

为了“填补空白”,您需要从某处获取信息。

在 mysql 中执行此操作的最简单方法是使用一些通用日历表,其中列出月份、年份等的单个值。

因此,给定一个表 months(month) 和一个表 years(year),前者包含 1..12 ,后者包含 2010..2017 (例如),我们可以交叉连接其中的两个来为我们提供每年的每个月,然后左连接 salary_raise 表到此。

这将为我们留下一个包含一些条目和大量空值的表,因此我们需要使用一些变量用最后一个工资条目填充null值。

select `year`, `month`, if(salary is null, @prev_sal, @prev_sal := salary) salary
from (
select `years`.`year`, `months`.`month`, salary
from `years` cross join `months`
left join salary_raise sr
on sr.month = `months`.`month`
and sr.year = `years`.`year`
and sr.employee_id = 1
where (`years`.`year` = 2014 or `years`.`year` = 2015)
order by `years`.`year` asc, `months`.`month` asc
) q cross join (select @salary := null) qq

demo here

当然,您需要限制它不检查 future 的日期 - 这应该很容易。

关于php - 用以前的值填充数组中的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com