你们好吗?我正在与一个存储员工工资,日期和电表读数的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的读数。
发布于 2019-10-16 23:26:46
我不知道每个月能有多少读数,所以我们把它们汇总起来。
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 */
;https://stackoverflow.com/questions/58415661
复制相似问题