在mysql中传播发票金额超过几个月

时间:2014-10-07 05:29:20

标签: mysql sql

我有一个包含start_date和end_date以及invoiced_amount的作业表。

例如:

id, company_id, start_date,   end_date,   invoice_amount, billed_at
1,  200,        2014-07-01,   2014-09-10, 999.00,         2014-10-01
2,  202,        2014-08-01,   2014-08-10, 1400.00,        2014-10-01

我想选择特定结算月份的每个月发票金额的份额(在此示例中为2014年10月)(例如,如果第一个月只是第一个月的一半,则分摊发票金额):

例如

id, company_id, 2014-07,   2014-08,   2014-09,  2014-10,  2014-11,  invoice_amount, billed_at
1,  200,        430.125,   430.125,   138.75,   0.00,     0.00,     999.00,         2014-10-01
2,  202,        0.00,      1400.00,   0.00,     0.00,     0.00,     1400.00,        2014-10-01

日期范围可能变化很大而且很大,但每个月应该在自己的列中,发票金额应根据月中的天数进行分摊(第一个月和最后几个月的天数也会考虑在内(这些天数)可能是月份的一半,例如))

1 个答案:

答案 0 :(得分:1)

它不是你想要的布局,但也许你可以使用

SELECT iv.*, 
       DATE_FORMAT(_date, '%M') AS month,
       COUNT(1) AS days, 
       ((iv.invoice_amount * count(1)) / (TIMESTAMPDIFF(DAY, iv.start_date, iv.end_date) + 1)) as monthly_amount
FROM (
        SELECT CURDATE() - INTERVAL (a.a + (10 * b.a) + (100 * c.a) + (1000 * d.a) + (10000 * e.a)) DAY AS _date
        FROM (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS a
        CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS b
        CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS c
        CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS d
        CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS e
     ) a INNER JOIN invoice iv
WHERE _date BETWEEN iv.start_date AND iv.end_date
group by iv.id, MONTH(_date)
ORDER BY iv.id, MONTH(_date);