I have data in table as below:
Account Id | Amount | Start_date | End_date |
---|---|---|---|
123 | 10 | 2023-11-16 17:00:00 | 2023-11-16 18:00:00 |
123 | 10 | 2023-11-16 02:00:00 | 2023-11-17 02:00:00 |
123 | 20 | 2023-11-17 17:00:00 | 2023-11-17 18:00:00 |
123 | 30 | 2023-11-18 02:00:00 | 2023-11-20 02:00:00 |
123 | 10 | 2023-11-18 17:00:00 | 2023-11-18 18:00:00 |
123 | 20 | 2023-11-19 02:00:00 | 2023-11-20 02:00:00 |
I need to calculate the amount for per day for one Cloud Id.
For ex – For Cloud Id 123, in the first row, the start date and end date has interval of 1 so amount of 10 will be included for date of 2023-11-16. The second row, the difference between start date and second day is 2, so the amount of 10 will be calculated for date of 16 as 10/2(difference) i.e. 2 and for date of 17 as 10/2 = 5.
11-16 10+5 = 15
11-17 5+20 = 25
11-18 10+10= 20
11-19 10+10= 20
I need to write a query to get the results in above way.
so far I have tried the following query but I am getting syntax error –
select start_date, end_date, account_id, amount, datediff(day, start_date, end_date) as interval into #temp
from billing where account_id = '123';
select * from #temp;
drop table if exists #result;
select account_id, start_date, end_date, interval,
CASE WHEN interval = 0 THEN amount ELSE amount/(interval + 1) END AS per_day_cost
INTO #result
UNION ALL
SELECT account_id, start_date, end_date, interval,
CASE WHEN interval = 0 THEN amount ELSE amount/(interval + 1) END AS per_day_cost
FROM (VALUES (1), (2), (3)) as v(n) CROSS JOIN
(SELECT account_id, start_date, end_date, interval, amount FROM #temp) s
where v.n <= interval
order by account_id;
select * from #result;
2
Answers
I ended up writing the following query for my question -
You can change a little bit your query (without using temporary tables)
I’ll add Id column to test table for clarity only.
For test data
result is
You can join table and "series" query v(n) in direct order