MySQL计算多个日期之间的价格范围内添加一次费用

y0u0uwnf  于 2023-11-16  发布在  Mysql
关注(0)|答案(1)|浏览(123)

我有一个不同时间段的价格表和一个标准价格表:

rates:
user_id | start | end | price | charges
1 | 2023-11-13 | 2023-11-19 | 100 | 25
1 | 2023-11-21 | 2023-11-23 | 120 | 30

rates_standard:
user_id | price | charges
1 | 75 | 20

个字符
通过这个查询,我得到了1060的sumprice

7 x 100 +
3 x 120
= 1060


如果查询的日期在季节之外,则应使用标准价格。另外,我想添加一次开始日期的费用。如果开始日期不在季节之内,则应使用标准费用。非常感谢您的帮助!

oxalkeyp

oxalkeyp1#

假设发布的代码按预期工作,那么扩展rates以在第一行之前和最后一行之后填充扩展,并在没有rates的地方包含rates_basic,这就是我的做法..https://dbfiddle.uk/uCJyLRm-

SET @START = '2023-11-13';
SET @end   = '2023-11-13';
set @uid = 1;

with cte as
(
select 0 as src,user_id,'1957-01-01' seasonstart, '1957-01-01' seasonend, price from rates_basic
union
select 10 as src,user_id,cast(@start as date) ss,
         date_sub(@minstart, interval 1 day) se,
         (select price from rates_basic rb where rb.user_id = r.user_id) price
from  rates r
where  @start < (select min(seasonstart) from rates where user_id = @uid)

union
select 20 as src,user_id,seasonstart,seasonend, price from rates
union
select 25 as src,user_id,
            date_add(seasonend,interval 1 day) seasonstar,
            date_sub(lead(seasonstart) over (partition by user_id order by seasonstart),interval 1 day) seasonend,
            (select price from rates_basic rb where rb.user_id = r.user_id) price
from rates r

union
select 30 as src,user_id,date_add(@maxend,interval 1 day) seasonstart,
         @end seasonend,
         (select price from rates_basic rb where rb.user_id = r.user_id) price
from  rates r
where  @end > (select max(seasonend) from rates where user_id = @uid)
) 

#select * from cte where src <> 0 and seasonend is not null

SELECT
SUM(
    DateDiff(
        Least(r.seasonend + INTERVAL 1 DAY, @end),
        Greatest(r.seasonstart, @start)
    ) * r.price
) price

FROM
  cte r
WHERE
  r.seasonend   >= @start AND
  r.seasonstart <  @end   and
  src <> 0 and r.seasonend is not null;

字符串
我使用用户定义的变量,因为我不想在代码中重新输入。你可能想创建一个函数,将这些变量作为参数传递给你的目的。src的值是为了帮助调试。
请看链接的结尾,看看cte中的内容。

相关问题