从MySQL的日期范围计算付款

时间:2012-04-03 10:17:59

标签: php mysql date

我想在选定的日期内计算付款,但我无法弄明白该怎么做。

以下是我表格中的示例数据

id    starts_from     payment_per_day
=======================================
1     2012-01-01      10,000.00
2     2012-01-15      10,500.00
3     2012-02-01      11,000.00
4     2012-02-15      11,500.00
5     2012-03-01      12,000.00

如何计算2012-01-21至2012-02-20的总付款额?

总付款应为338,500

from 2012-01-21 to 2012-01-31 = 11 days * 10,500
from 2012-02-01 to 2012-02-14 = 14 days * 11,000
from 2012-02-15 to 2012-02-20 =  6 days * 11,500

但如果我这样做:

SELECT SUM(payment_per_day) as total FROM table 
WHERE starts_from BETWEEN '2012-01-21' AND '2012-02-20'

结果只有22,500

有什么想法吗?

3 个答案:

答案 0 :(得分:5)

SELECT SUM(payment_per_day) as total FROM table 
WHERE starts_from BETWEEN '2012-01-21' AND '2012-02-20';

答案 1 :(得分:2)

我首先将范围扩展到日期列表中,然后使用以下查询:

SELECT SUM(p1.payment_per_day)
FROM dates d
  INNER JOIN payments p1 ON p1.starts_from <= d.date
  LEFT  JOIN payments p2 ON p2.starts_from <= d.date
                        AND p2.starts_from > p1.starts_from
WHERE p2.id IS NULL

您可以在数字表的帮助下从范围中获取列表,如下所示:

SELECT DATE_ADD(@date_from, INTERVAL num DAY)
FROM numbers
WHERE num BETWEEN 0 AND DATEDIFF(@date_to, @date_from)

数字表是值得拥有的,因为它在许多情况下都很有用,所以请考虑为自己提供一个。这是一个非常简单的脚本来创建和初始化数字表:

CREATE TABLE numbers AS SELECT 0 AS num;
SET @ofs = (SELECT COUNT(*) FROM numbers); INSERT INTO numbers SELECT @ofs + num FROM numbers;
SET @ofs = (SELECT COUNT(*) FROM numbers); INSERT INTO numbers SELECT @ofs + num FROM numbers;
SET @ofs = (SELECT COUNT(*) FROM numbers); INSERT INTO numbers SELECT @ofs + num FROM numbers;
… /* repeat as necessary, each line doubles the number of rows in the table */

但是,当然,你可以改用循环。

Here's我在SQL Fiddle上的完整测试环境(任何人都可以玩)。

答案 2 :(得分:0)

似乎几乎不可能像这样进行查询,在所选日期内计算每天的总付款。

因此,我选择从所有starts_from日期开始直到&lt; = 2012-02-20的数据,然后选择最后的starts_from日期,该日期小于2012-01-21(即2012-01-15),以便获得payment_per_day 10,500.00

感谢您查看我的问题:)