计算日期差异的金额

时间:2010-08-23 10:35:48

标签: php mysql sql

我有一个包含两列的表,如图所示

alt text

执行页面用户时输入开始和结束日期。

现在我需要计算的是总金额。

例如,如果用户输入

      start date: 18-jan-2010
      end date: 23-jan-2010

然后他在第一个选项(20 $)中有2个日期,在第二个选项中有3个日期(26 $),所以总计将是(56 $)。

首先我要在sql中计算

1. how many days in first range (if any this depends on supplied dates from user)
2. how many days in 2nd range  (if any this depends on supplied dates from user)
3. how many days in 3rd range  (if any this depends on supplied dates from user)

然后

我们将使用php中的Amount乘以每个范围的数量。

最后我想在php中获得总计。

2 个答案:

答案 0 :(得分:2)

也许:

SELECT SUM(amount) FROM your_table WHERE date BETWEEN start_date AND end_date GROUP BY user

答案 1 :(得分:0)

SELECT 'In Range' AS SumType
       SUM(amount) 
  FROM <table> 
 WHERE date BETWEEN start_date AND end_date
UNION
SELECT 'Outside Range' AS SumType
       SUM(amount) 
  FROM <table> 
 WHERE date < start_date OR date > end_date
UNION
SELECT 'Grand Total' AS SumType
       SUM(amount) 
  FROM <table>