如何在mysql

时间:2019-10-16 14:25:24

标签: mysql

大家好?我正在使用一个MySQL表来存储员工的工资,日期和电表读数。我想选择上个月的读数作为上个月的读数,将本月的读数选择为当月的读数,这就是我的意思。

 payno | date       | value 
-------+------------+------------
 6     | 2019-08-31 | 2477
 6     | 2019-09-25 | 2487
 8     | 2019-08-31 | 1651.2
 8     | 2019-09-25 | 1697.6

上面是我的表的结构,我想要实现以下功能:

 payno | previous month| current month
-------+---------------+------------
 6     | 2477          | 2487
 8     | 1651.2        | 1697.6

请注意,上个月的读数是月份(日期)为8的读数,而当前月份的读数是月份(日期)为9的读数。

1 个答案:

答案 0 :(得分:1)

我不知道每月可以读取多少个数据,因此我们将对其进行汇总。

select e.payno,
(   select sum(x1.val) 
    from emp x1 
    where x1.payno=e.payno and month(x1.data)=month(date_sub(e.data, INTERVAL 1 MONTH))
    group by x1.payno ) AS prev_month,
(   select sum(x2.val) 
    from emp x2 
    where x2.payno=e.payno and month(x2.data)=month(e.data)
    group by x2.payno ) AS this_month
from emp e
where month(e.data)=9 /* this is where you specify "current" month */
;
相关问题