获取客户致电的总费用

时间:2019-06-26 18:12:50

标签: mysql sql

我有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月的数据,但仍受此方法困扰。

1 个答案:

答案 0 :(得分: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)
            ELSE 2*(h.duration-120)
       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)
            ELSE 2*(h.duration-120)
       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