【问题标题】:Get total cost for a customer call获取客户通话的总费用
【发布时间】:2019-11-08 18:04:58
【问题描述】:

我有 2 个表 = 客户及其通话记录

现在我想根据通话时长以及特定月份(比如 2015 年 1 月)向他们收费。

这是计算通话费用的标准 -

A) 对于来电,收费为每秒 1 个单位。 Example if the duration is 250 seconds then cost is 250

B) 对于拨出电话,for the first 2mins, the cost is fixed at 500 units。随后几秒钟的费用为2 units per second

例如,如果传出持续时间为 5 分钟,则费用为 500 units + 2*3*60 units = 860 units

下表是:

customer table with columns id, name, phone

history table with columns id, incoming_phone, outgoing_phone, duration, dialed_on (YYYY-MM-DD)

我针对我的情况提出了以下查询:

来电费用:

select c.name, c.phone, h.duration as cost
from customer c join history h on c.phone = h.incoming_phone

当我运行上述查询时,我没有收到任何语法错误。

拨出电话费用:

select c.name, c.phone, CASE
    WHEN h.duration > 120 THEN 500 + 2*(h.duration-120)
    ELSE 2*(h.duration-120)
END; as cost
from customer c join history h on c.phone = h.outgoing_phone

当我运行上述查询时,我得到了syntax error like "ERROR 1109 (42S02) at line 1: Unknown table 'c' in field list"

我想加入这两个查询并获取总费用并将字段显示为姓名、电话、费用

我仍然需要为特定月份添加一个条件来限制 2015 年 1 月的数据,但我被这个方法卡住了。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    错误是由于END 后面的分号; 造成的。

    听起来您的最终查询是这样的:

    SELECT c.name, 
           c.phone, 
           SUM(CASE WHEN h.direction = 'in' THEN h.duration END) as IncomingCost,
           SUM(CASE WHEN h.direction = 'out' AND h.duration > 120 THEN 500 + 2*(h.duration-120)
                    WHEN h.direction = 'out' AND h.duration <= 120 THEN 500
           END) as OutgoingCost,
           SUM(CASE WHEN h.direction = 'in' THEN h.duration END +
           CASE WHEN h.direction = 'out' AND h.duration > 120 THEN 500 + 2*(h.duration-120)
                WHEN h.direction = 'out' AND h.duration <= 120 THEN 500
           END) as TotalCost
    FROM customer c 
    JOIN (SELECT 'out' as directon, duration, dialed_on, outgoing_phone as phone 
          FROM history 
          WHERE YEAR(dialed_on) = 1995
          AND MONTH(dialed_on) = 1
          UNION ALL
          SELECT 'in' as direction, duration, dialed_on, incoming_phone as phone
          FROM history
          WHERE YEAR(dialed_on) = 1995
          AND MONTH(dialed_on) = 1
         ) h ON c.phone = h.phone
    GROUP BY c.name,
             c.phone
    

    【讨论】:

    • 来电费用,我必须加入incoming_phone,去电费用我必须加入outgoing_phone
    • @learner 哎呀,忽略了这一点。可能最简单的解决方法是使用 union 规范化该结构,然后为每个调用方向的总和添加一个额外条件。
    • 如何合并两个查询并计算总成本
    • @AaronDietz 嘿,为什么你有 (duration - 120) * 2 这会产生负成本?如果持续时间少于 2 分钟,不应该只是 500 的固定成本吗
    • @AaronDietz 你现在可以解决这些问题;)
    猜你喜欢
    • 2019-12-17
    • 2020-12-11
    • 2014-07-24
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多