获取客户致电的总费用

学习者

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

亚伦·迪茨(Aaron Dietz)

该错误是由于;后面有多余的分号引起的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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章