计算每天的会员收入

时间:2012-12-04 09:19:03

标签: mysql

我有一个包含colums ID,Start_date,End_date,Duration,Value

的成员资格表
ID | Start_date | End_date | Duration | Value |
1  | 2012-08-12 |2012-09-12|    30    |   10  |
2  | 2011-05-22 |2013-05-22|   720    |  2000 |

等等

我希望将其分为两个列,一个具有日期,一年中的每一天,另一个具有当天所有会员资格的值/持续时间的总和。

我最终需要将其转化为每月价值,让我清楚地了解未来会因会员资格而获得的收入。

现在我做了类似

的事情
select 
sum(if("2012-01-01" between start_date and end_date, total_value/duration, null)) as "2012-01-01",
sum(if("2012-01-02" between start_date and end_date, total_value/duration, null)) as "2012-01-02",
[...]
sum(if("2013-12-31" between start_date and end_date, total_value/duration, null)) as "2013-12-31"

from MembershipsTable

/ * 0行受影响,找到1行。 1次查询的持续时间:3,666秒。 * /

但我不知道如何轻松总结它们给我一个月的价值。我可以再次创建列的总和,但不必键入文本小说

运行时间不是当前格式的问题

我需要一个形状

的输出
Month    | Sum    |
Jan 2012 |4500    |
Feb 2012 |4215,91 |

如果总和是与每天的价格相关的所有会员的总和*会员在该月的天数。

因此,如果会员资格从11月12日开始,12月11日结束,持续时间为30,价值为300,我想在11月添加300/30 *天数,同样为12月,给我11月+190, 12月+110 我需要以这种方式获得所有会员资格的总和。

有没有人有任何想法?

1 个答案:

答案 0 :(得分:1)

这是一个丑陋的黑客,但我相信如果我正确理解你的需求,下面的内容就会奏效。

首先,创建一个名为month_days的表格,其中包含所有月份的开始日期和结束日期。您可以将其用作实用程序表来加入并计算每月总计。

month_days
start_date | last_date 
2012-01-01 | 2012-01-31
2012-02-01 | 2012-02-29

然后,执行连接并计算如下:

select format(month_days.start_date, 'MMM yyyy') AS [Month],
       sum(case when (memberships.start_date > month_days.start_date AND memberships.end_date < month_days.end_date)
              then datediff(day, memberships.end_date, memberships.start_date) * (value/duration)
            when (memberships.start_date between month_days.start_date and month_days.end_date)
              then (datediff(day, month_days.end_date, memberships.start_date) + 1) * (value/duration)
            when (memberships.end_date between month_days.start_date and month_days.end_date)
              then datediff(day, memberships.end_date, month_days.start_date) * (value/duration)
            else (datediff(day, month_days.end_date, month_days.start_date) + 1) * (value/duration)
        end) total_value
from memberships
inner join month_days
on memberships.start_date < month_days.end_date
and memberships.end_date > month_days.start_date
group by month_days.start_date
order by month_days.start_date

有很多方法可以创建一个可以达到类似效果的month_days表。

您可能还可以编写一个存储过程来迭代每个记录的月份,使用每月总和填充临时表(或表变量),然后返回临时表的内容。