gpt4 book ai didi

mysql - 计算当月的账单使用情况

转载 作者:可可西里 更新时间:2023-11-01 08:09:00 24 4
gpt4 key购买 nike

我正在尝试计算当月的存储空间使用情况。表格的外观如下:

stored_on              deleted_on          amount_in_gb    rate_per_gb_per_month
2014-01-01 12:00:00 2014-05-09 00:00:00 20 0.05
2015-01-01 00:00:00 NULL 4.2 0.05
2015-01-01 12:00:00 2015-01-09 00:00:00 7.2 0.05
2016-01-01 12:00:00 NULL 100 0.05

要获取 2015 年 1 月的使用量,它将是:

  $0.05 * 20 * 0        = $0.00 (this item was deleted before the start of the month)
+ $0.05 * 4.2 * 1 = $0.21 (for the second line item, the item is stored for a full month)
+ $0.05 * 7.2 * (~8/31) = $0.09 (stored for about 8 of 31 days in the month)
+ $0.05 * 100 * 0 = $0.00 (this item was added after this month)
---------------------------------
TOTAL = $0.30

我将如何在 SQL 中执行上述操作?基本上,给定一个特定的月份,计算该月的使用情况,考虑到 stored_on 值可能在该月开始之前、该月期间或该月之后的事实;与 deleted_on 值相同。

最佳答案

这应该计算一月份的按比例分配的金额:

select sum( rate_per_gb_per_month * amount_in_gb *
greatest(1 +
datediff(least('2015-01-31', coalesce(deleted_on, '2015-01-31')) ,
greatest('2015-01-01', stored_on)
), 0
) / DAY(LAST_DAY('2015-01-01'))
) as usage_cost

from t;

Here是一个 SQL fiddle 。

关于mysql - 计算当月的账单使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51529962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com