Siwan
Siwan

Reputation: 59

Counting payment from date range in MySQL

I want to count payment within selected date, but i can't figure it out how to do it.

Here is the example data from the my table

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

How do i count total payment from 2012-01-21 to 2012-02-20 ?

The total payment should be 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

But if i do :

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

the result is only 22,500

Any ideas ?

Upvotes: 2

Views: 367

Answers (3)

Andriy M
Andriy M

Reputation: 77677

I would first expand the range into the list of dates, then use the following query:

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

You could obtain the list from the range with the help of a numbers table, like this:

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

A numbers table is a thing worth having as it can be useful in many situations, so consider providing yourself with one. Here's a very simple script to create and initialise a numbers table:

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 */

But, of course, you can use a loop instead.

Here's my complete testing environment on SQL Fiddle (for anyone to play with).

Upvotes: 2

Siwan
Siwan

Reputation: 59

It seems that it is almost impossible to do query like that, counting total each day payment within selected date.

So i work around by selecting data from all starts_from dates until <= 2012-02-20 and then picking last starts_from date which is less than 2012-01-21 (that is 2012-01-15) in order to get payment_per_day 10,500.00

Thank you for viewing my question :)

Upvotes: 0

xdazz
xdazz

Reputation: 160843

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

Upvotes: 5

Related Questions