簡體   English   中英

每天計算會員收入

[英]Calculating membership revenue per day

我有一個成員表,具有列ID,開始日期,結束日期,持續時間,值

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,我想將300/30 * daysInNov添加到11月,與12月相同,給我11月+190,11月+110十二月我需要這種方式的所有成員加總。

有人有什么主意嗎?

這有點丑陋,但是我相信,如果我正確地理解了您的需求,下面的內容將會起作用。

首先,創建一個名為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表,從而可以達到類似的效果。

您可能還可以編寫一個存儲過程,以遍歷每個記錄的月份,用每月的總和填充臨時表(或表變量),然后返回臨時表的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM