MYSQL中的多个选择,计数和位置语句

时间:2017-01-31 14:32:54

标签: mysql select count group-by

我正在尝试生成一个与图表一起使用的报告,我尝试了很多不同的陈述,但却无法让它发挥作用。

基本上,我希望能够显示我的数据库中的呼叫记录,按日期分组,并计算以提供准确的图片。

| Date     | Answered Calls | Missed Calls | Total Calls |
| 1-1-2016 | 10             | 2            | 12
| 2-1-2016 | 15             | 1            | 16

Etc等

但是,使用以下声明(这不包括总呼叫计数),我会继续获得以下内容 -

SELECT  (SELECT DATE(`created`)
         FROM   mp_wp_call_report_pstn
        ) AS created_date,

        (SELECT `Extension`
         FROM   mp_wp_call_report_pstn
        ) AS Extension,

        (SELECT COUNT(*)
         FROM   mp_wp_call_report_pstn
         WHERE `Call type` = "Incoming" 
               AND `Extension` != 2504 
               AND `created` >= DATE_SUB(CURDATE(),INTERVAL 1 MONTH)
        ) AS CallsAnswered,

        (SELECT COUNT(*)
         FROM   mp_wp_call_report_pstn
         WHERE `Call type` = "Incoming" 
         AND `Extension` = 2504 
         AND `created` >= DATE_SUB(CURDATE(),INTERVAL 1 MONTH)
        ) AS CallsRecieved

GROUP BY DATE(`created_date`) 
LIMIT 0, 25
  

MySQL说:文档 - #1064 - 你的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以获得在' GROUP BY附近使用的正确语法       日期(created_date)限制0,25和#39;在第22行

为了接听未接来电,我们只收到收到的回复。

非常感谢任何建议。

2 个答案:

答案 0 :(得分:0)

您需要的一切都在一张桌子里。你不应该使用子查询。

将日期和call_type条件推送到where子句,并按电话日期分组。

这样的事情会让你走上正轨:

select DATE(`created`) as created_date,
  sum((case when (`Extension` != 2504) then 1 else 0 end)) AS CallsAnswered,
  sum((case when (`Extension` = 2504) then 1 else 0 end)) AS CallsReceived,
  count(*) as total_calls
from mp_wp_call_report_pstn
where `created` >= DATE_SUB(CURDATE(),INTERVAL 1 MONTH)
  and `Call type` = "Incoming"
group by created_date

答案 1 :(得分:0)

您不需要所有这些子查询,只需计算不同的呼叫并按日期和分组进行分组。

SELECT DATE(`created`) AS created_date, 
       `Extension`,
       SUM(CASE WHEN `Call type` = "Incoming" 
                     AND `Extension` != 2504 
                     AND `created` >= DATE_SUB(CURDATE(),INTERVAL 1 MONTH)
           THEN 1 ELSE 0 END) AS CallsAnswered,
       SUM(CASE WHEN `Call type` = "Incoming" 
                     AND `Extension` = 2504 
                     AND `created` >= DATE_SUB(CURDATE(),INTERVAL 1 MONTH)
            THEN 1 ELSE 0 END) AS CallsRecieved
FROM mp_wp_call_report_pstn
GROUP BY DATE(`created`), `Extension`
LIMIT 0, 25;