如何按月汇总MYSQL中的已支付账单和SUM总额

时间:2016-09-06 20:25:56

标签: mysql sql sum

当我选择一个表的值

SELECT 
    DATE_FORMAT(created,'%Y-%m')
    ,DATE_FORMAT(payday,'%Y-%m')
    ,SUM(IF(paid = 'S',total,0)) as total_paid_on_this_month
    ,SUM(IF(paid = 'N',total,0)) as total_debt_on_this_month_plus_anterior_months
FROM bills
GROUP BY DATE_FORMAT(created,'%Y-%m')

表格账单

+ ---------- + ---- + ---------- + ------ + ----- +
| created    | paid | data_paid  | by     | total |
+ ---------- + ---- + ---------- + ------ + ----- +
| 2016-05-03 | Y    | 2016-08-03 | amy    | 10,00 |
| 2016-06-10 | Y    | 2016-07-03 | jorge  | 20,00 |
| 2016-05-20 | N    | 0000-00-00 |        |  5,00 |
| 2016-07-05 | N    | 0000-00-00 |        |  0,00 |
+ ---------- + ---- + ---------- + ------ + ----- +

我需要的是每月BILL的总和(前一个月的总额)和总支付(仅支付的月份)

示例:

one bill(10,00) was created at month 1 and paid at month 4

所以

another bill(20,00) was created at month 2 and not paid yet

我需要什么

month 1      2      3      4
paid  00,00  00,00  00,00  10,00
bill  10,00  30,00  30,00  20,00

我得到了什么

month 1      2      3      4
paid  00,00  00,00  00,00  10,00
bill  10,00  20,00  00,00  20,00

我试过

SELECT
    created as Start
    ,total
    ,DATE_FORMAT(IF(paid = 'S',data_paid,CURRENT_TIMESTAMP()),'%Y-%m') as End

FROM 'Bills'

并在foreach

中的PHP上加以总结

有人可以帮助我做到这一点吗?

我看到了什么:

SQL: SUM the MAX values of results returned

How I get OR to SUM(IF()) MySQL

https://www.techonthenet.com/mysql/functions/sum.php

0 个答案:

没有答案