我希望这只是我的格式错误,所以我不会发布更多我的查询而不是必要的。
我有一个包含多个连接和多个SUM参数的大型查询(此查询的目的是在每次运行时聚合每日总计)。
这是我的麻烦行:
sum(case when (duration > 60 and LEGTYPE1 = 1) then 1 else 0 end)
我也试过这个:
count(case when (duration > 60 and LEGTYPE1 = 1) then 1 else null end)
这是问题:总和案例返回1或0,计数行确实返回计数(13,14,16),但它不是我记录的正确数字。
以下是上下文的整个查询:
SELECT c.extension
, sum(Duration) AS Total_Talk_Time_seconds
, round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes
, sum(if(LEGTYPE1 = 1,1,0)) AS Total_Outbound
, sum(if(LEGTYPE1 = 2,1,0) and ANSWERED = 1) AS Total_Inbound
, sum(if(Answered = 1,0,1)) AS Total_Missed
, SUM(IF(LEGTYPE1 = 1, 1, 0)) + -- outbound calls
SUM(IF(LEGTYPE1 = 2, 1, 0) AND ANSWERED = 1) + -- inbound calls
SUM(IF(Answered = 1, 0, 1)) AS Total_Calls
, NOW() AS Time_of_report
, curdate() AS Date_of_report
FROM cdrdb.session a
INNER JOIN cdrdb.callsummary b
ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join cdrdb.mxuser c
ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
WHERE b.ts >= curdate()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)
group by c.extension
因此,当我执行该行的计数版本时,该数字与调用的总数相匹配,其中它应仅表示持续时间超过60秒的出站数。数据是正确的,字段是正确的,我只是问我的语法是否正确,或者只是有一种更好的方法来构建它。
答案 0 :(得分:-1)
不确定我是否遵循您的逻辑,但是:
sum(if(LEGTYPE1 = 2,1,0) and ANSWERED = 1) AS Total_Inbound
和
SUM(IF(LEGTYPE1 = 2, 1, 0) AND ANSWERED = 1) +
SUM(IF(Answered = 1, 0, 1)) AS Total_Calls
似乎错了。尝试:
sum(if(LEGTYPE1 = 2 and ANSWERED = 1, 1, 0) AS Total_Inbound
和
SUM(IF(LEGTYPE1 = 2 AND ANSWERED =1 , 1, 0) +
IF(Answered = 1, 0, 1)
) AS Total_Calls