如何按每年每个月的结束日期获取数据?

时间:2018-11-07 07:20:31

标签: 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

我尝试过的方法行得通,但是当想要按montly分组时却不需要输出

$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 条件并将其相应地分组以获得所需的输出?

任何想法还是有可能实现?谢谢。

2 个答案:

答案 0 :(得分:1)

这是滚动汇总问题。在更新版本的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

答案 1 :(得分:0)

如果要使用变量,则需要正确执行。 MySQL不保证SELECT中表达式的求值顺序。因此,不应在一个表达式中分配变量,而在另一个表达式中使用该变量。

这使表达式变得复杂,但是有可能:

select yyyy, mm, total,
       (@t := if(@ym = concat_ws('-', yyyy, mm), @t + total,
                 @ym := concat_ws('-', yyyy, mm), total
                )
       ) as running_total                 
from (select year(created_at) as yyyy, month(created_at) as mm,
             id_item, 
             sum(case T_IN when 1 then qty else - qty end) as total 
      from transactions 
      where created_at < '2018-11-01'
      group by id_item
      order by id_item, min(created_at)
     ) i cross join
     (select @ym := '', @n := 0);