我有一个名为“租金”的表,我在其中存储如下数据:
id | rent_id | start_date | end_date | amount
---------------------------------------------
1 | 54 | 12-10-2019 | 26-10-2019| 100
2 | 54 | 13-10-2019 | 20-10-2019| 150
我期望什么?结果如下:
12-10-2019 , amount 100
from 13-10-2019 to 20-10-2019, amount 250
from 21-10-2019 to 26-10-2019, amount 100
基本上我想要每一天的金额总和。但我也想计算“之间的天数”。
所以预期的结果是:
id | rent_id | day | amount
---------------------------------------------
1 | 54 | 12-10-2019 | 100
2 | 54 | 13-10-2019 | 250
3 | 54 | 14-10-2019 | 250
等等……
我实际上正在运行以下 sql:
select start_date, ( select sum(amount) from rentals as t2 where t2.start_date <= t1.start_date) as amount from rentals as t1 WHERE rent_id = 54 group by start_date
但结果并不像预期的那样......
我正在使用 MySQL。
最佳答案
我认为这可能有帮助 使用 MSSQL
declare @startDate date ='11 Oct 2019'
declare @endDate date ='30 Oct 2019'
declare @rentId nvarchar(50)='54'
select d.Day,d.rent_id,isnull(d.amount,0) as amountPaid, amount = SUM(d.amount) OVER (ORDER BY d.Day) from (
select c.Day,c.id,case when rent_id is null then @rentId else rent_id end as rent_id,c.amount from (
select * from (
SELECT DATEADD(DAY,number+1,@startDate) [Day]
FROM master..spt_values
WHERE type = 'P'
AND DATEADD(DAY,number+1,@startDate) < @endDate
) a left join (select * from rentals where rent_id=@rentId) b on a.[Day] = b.start_date) c) d
关于mysql - 每个日期的 SQL 总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58352963/