php - 如何获取一年中每个月结束日期的数据?

标签 php mysql sql eloquent

这是我的表格中的示例数据

id_item | qty | t_in | t_out | created_at
 1         5     1       0    2018-07-05 10:41:00
 1         5     1       0    2018-08-03 10:41:00
 1         5     0       1    2018-08-05 10:41:00
 1         5     1       0    2018-09-05 10:41:00
 1         5     1       0    2018-09-20 10:41:00
 1         5     0       1    2018-10-31 10:41:00

我的预期结果是

id_item | qty | year | month
 1         5    2018   07
 1         5    2018   08
 1         15   2018   09
 1         10   2018   10

我尝试过的方法有效,但当想要按月分组时不是所需的输出

$date = '2018-10-31'
$test = Model::whereDate('created_at','<=',$date)->select(DB::raw('(SUM(CASE T_IN WHEN 1 THEN qty ELSE qty * - 1 END)) as total'))->groupBy('id_item')->get();

获取一个月数量的原始查询

Select id_item, 
       (SUM(CASE T_IN WHEN 1 THEN qty ELSE qty * - 1 END)) as total 
from transactions 
where DATE(created_at) <= 2018-10-31 
group by id_item

最坏的情况

$last_day_of_month = [//list of last day of each month]
//then using loop to get qty of each month refer to the raw queries above

从上面的查询中,我只能得到一行记录。我还尝试按月和年分组,但由于日期条件导致结果不正确。我如何包含多个 <= $date 条件并相应地对其进行分组以获得所需的输出?

有什么想法或者可以实现吗?谢谢。

最佳答案

这是一个滚动求和问题。在较新版本的 Mariadb/MySQL 中,可以使用带有框架的窗口函数来解决。然而,you don't have that available .

我们可以使用用户定义的变量来解决这个问题。在派生表中,我们首先确定一个月qty 的总变化。然后,我们使用此结果集计算月末的“最终数量”,方法是将上个月(行)的 qty 与当月(行)的 相加>qty_change

我还扩展了查询以考虑存在多个 id_item 值的情况。

尝试以下原始查询:

SELECT 
  @roll_qty := CASE WHEN @id_itm = dt.id_item 
                    THEN @roll_qty + dt.qty_change 
                    ELSE dt.qty_change  
               END AS qty, 
  @id_itm := dt.id_item AS id_item, 
  dt.year, 
  dt.month 
FROM 
(
 SELECT 
   t.id_item, 
   SUM(t.qty * t.t_in - t.qty * t.t_out) AS qty_change, 
   YEAR(t.created_at) AS `year`, 
   LPAD(MONTH(t.created_at), 2, '0') AS `month`
 FROM your_table AS t 
 GROUP BY t.id_item, `year`, `month`
 ORDER BY t.id_item, `year`, `month` 
) AS dt 
CROSS JOIN (SELECT @roll_qty := 0, 
                   @id_itm := 0
           ) AS user_init_vars;

| id_item | year | month | qty |
| ------- | ---- | ----- | --- |
| 1       | 2018 | 07    | 5   |
| 1       | 2018 | 08    | 5   |
| 1       | 2018 | 09    | 15  |
| 1       | 2018 | 10    | 10  |

View on DB Fiddle

关于php - 如何获取一年中每个月结束日期的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53185025/

相关文章:

mysql - 根据嵌套查询的结果替换 sql 查询中的值

php - 使用 cURL 通过 POST 和 MULTIPART/FORM-DATA 执行流(逐行)文件上传

php - 分页的原始脚本

mysql - 在 where 子句中的计数内使用 select

mysql - 你如何调试 MySQL 存储过程?

php - 如何在 MySQL 列类型 varchar(1000) 中正确写入文本?

php join 多个查询结果 laravel

javascript - 将 HTML 文件内容传递给 JavaScript 变量

python - 用户名 密码找回

mysql - SQL - 将组元素转换为新列