找到2个日期之间的金额总和

时间:2014-09-17 10:12:05

标签: mysql

我的桌子付款包含ID,金额,日期。 我需要计算2个日期之间的总金额。 我有一个表格,用户输入开始日期和结束日期。我需要计算两个日期之间的总金额..

QUERY

$result = mysql_query("SELECT sum(amount) 
                       FROM payment 
                       WHERE (date BETWEEN '$date' and '$date1')");
I m getting the wrong sum..

这是从数据库中获取的记录

提供的总金额:600

Membership No |  Month    |  Date        |  Amount
--------------+-----------+--------------+-----------
14015         |  October  | 2014-09-13   |   600
14017         |  October  | 2014-09-14   |   400
14013         |  October  | 2014-09-17   |   100
14015         |  November | 2014-09-17   |   500

3 个答案:

答案 0 :(得分:0)

您可以尝试格式化日期变量,例如 - `

  $date="13-09-2014";
    $date1="17-09-2014";

    $date=date_format ( $date, 'Y-m-d' );
    $date1=date_format ( $date1, 'Y-m-d' );

    $result = mysql_query("SELECT sum(amount) 
                       FROM payment 
                       WHERE (date BETWEEN '$date' and '$date1')");

`

答案 1 :(得分:0)

QUERY -

        SELECT sum(amount) FROM payment WHERE date BETWEEN  
        STR_TO_DATE('$date','%m/%d/%Y') 
        and 
        STR_TO_DATE('$date1','%m/%d/%Y')

SQL FIDDLE DEMO

答案 2 :(得分:0)

将输入格式设为“dd MMM yyyy”

"SELECT sum(amount) 
                   FROM payment 
                   WHERE (cast(date as nvarchar(12) BETWEEN '$date' and '$date1')"

"SELECT sum(amount) 
                   FROM payment 
                   WHERE (convert(nvarchar(12),date,106) BETWEEN '$date' and '$date1')"