Mysql查询计算总成本

时间:2011-04-26 12:06:48

标签: mysql

HI 我有一个表listsing_prices(id,listing_id,day_from,day_to,price) 我需要在mysql中计算假期的总费用,因为我需要按总费用对结果进行排序。

EX:

VALUES IN TABLE
1  6   2011-04-27   2011-04-30   55,00
2  6   2011-05-01   2011-05-02   60,00
3  6   2011-05-03   2011-05-15   65,00

假期从2011-04-28到2011-05-05总费用= 480

3 个答案:

答案 0 :(得分:0)

select count(price) from listing_prices where day_from >= '2011-04-28' and day_to <= '2011-05-05'

答案 1 :(得分:0)

-- This will provide a list of ids along with how many days fall between the two
SELECT a.id, DATEDIFF(DAYS, CASE WHEN day_from < '2011-04-28' THEN '2011-04-28' ELSE day_from END CASE, day_to) AS DayCount
FROM listing_prices a
WHERE '2011-04-28' BETWEEN a.date_from AND a.date_to
    AND a.date_to <= '2011-05-05'

-- Based on the previous query, sum the number of days within the range
SELECT SUM( a.price * b.DayCount ) AS Total
FROM listing_prices a
JOIN ( SELECT a.id, DATEDIFF(DAYS, CASE WHEN day_from < '2011-04-28' THEN '2011-04-28' ELSE day_from END CASE, day_to) AS DayCount
FROM listing_prices a
WHERE '2011-04-28' BETWEEN a.date_from AND a.date_to
    AND a.date_to <= '2011-05-05'

)b ON a.id = b.id

请注意,这是未经测试的...顶部的查询我认为应该可以工作,但如果没有,可以修改它,以便它确实有效(获取每个范围内的天数)然后字面上复制并粘贴到第二个查询的子查询中。第二个查询是您实际使用的查询。

答案 2 :(得分:0)

如果不创建实际表来表示从开始日期到结束日期的每一天,您可以使用mysql查询变量。第一个查询可以加入到任何表中,只要它与您在周末期间所关注的天数一样多...在这种情况下,从4月28日到5月5日为止8天。通过做笛卡尔并限制为8从本质上讲,从2011/04/28(您的开始日期)开始,每天创建一个包含一条记录的临时结果集。

然后,这会返回到与日期相匹配的定价表,并将总成本的匹配价格相加...

select  
        sum( pt.price ) as TotalCosts
    from 
        ( SELECT 
                 @r:= date_add(@r, interval 1 day ) CalendarDate
            FROM 
                 (select @r := STR_TO_DATE('2011/04/28', '%Y/%m/%d')) vars,
                AnyTableWithAtLeast8ays limit 8 ) JustDates,
        PricesTable pt
    where
        JustDates.CalendarDate between pt.date_from and pt.date_to