MySQL按比例计算上一期间的不同值

时间:2011-12-18 14:45:36

标签: mysql count sum distinct

这一点非常棘手,我整天都在摸不着头脑。

我有一个包含结算周期的表格

ID     | DATEBEGIN | DATEEND  | CUSTOMER_ID
=======+===========+==========+=================
1      | 1/1/2011  | 30/1/2011 | 1

我有一个包含'子客户'的表

ID     | NAME    
=======+===========
1      | JOHN
2      | JACK
3      | Elwood

我有一张表格,其中包含在订阅上购买的商品(批发帐户

ID     | DATE      | SUBCUSTOMER_ID | CUSTOMER ID
=======+===========+================+==============
1      | 15/1/2011 | 1              | 1
2      | 18/1/2011 | 1              | 1
3      | 25/1/2011 | 2              | 1
4      | 28/1/2011 | 3              | 1

所以我想从他们的帐户中扣除“积分”。因此,订阅是按照“子客户”进行的。

因此,在结算周期结束时(第一张表格从2011年1月30日开始)。我需要计算不同的子客户(有3个)。它们是在结算期间首次购买时按比例收取的。

Days Having Subscription  |  SUBCUSTOMER_ID   |  Pro Rata Rate   | CUSTOMER_ID
==========================+===================+==================+==============
3                         |  3                | 3/30             | 1
6                         |  2                | 6/30             | 1
16                        |  1                | 16/30            | 1

因此输出应为

CUSTOMER_ID | BILLING CREDITS
============+========================
1           | 25/30

我必须按比例计算,以前即使他们在结算日期前一天购买商品,也需要支付一段时间才是不公平的

2 个答案:

答案 0 :(得分:0)

SELECT  customerId, SUM(DATEDIFF(dateend, fp) + 1) / (DATEDIFF(dateend, datestart) + 1)
FROM    (
        SELECT  b.*, MIN(date) AS fp
        FROM    billing b
        JOIN    purchase p
        ON      p.customerId = b.customerId
                AND p.date >= b.datebegin
                AND p.date < b.dateend + INTERVAL 1 DAY
        GROUP BY
                b.id, p.subcustomerId
        ) q
GROUP BY
        customerId

答案 1 :(得分:0)

SELECT customer_id, sum(pro_rated_date) / max(days_in_billing_cycle)
  FROM (SELECT min(date),
               subcustomer_id,
               datebegin,
               dateend,
               items.customer_id,
               datediff(dateend, datebegin) + 1 AS days_in_billing_cycle,
               datediff(dateend, min(date)) AS pro_rated_date
          FROM    items
               JOIN
                  billing_period
               ON items.date BETWEEN billing_period.datebegin
                                 AND billing_period.dateend
                  AND items.customer_id = billing_period.customer_id
        GROUP BY subcustomer_id) AS billing
GROUP BY customer_id