我需要总结从输入日期开始的过去8周(但每周)每个msisdn发送的消息数量。以下是我提出的建议:
SELECT count(*) as ukupan_broj, SUM(IF (sent_messages.delivered = 1,1,0 )) as broj_dostavljenih,
count(*) - SUM(IF (sent_messages.delivered = 1,1,0 )) as non_billed,
SUM(IF (sent_messages.delivered = 1,1,0 )) / count(*) as ratio,
`sent_messages`.`msisdn`,
MONTH(`sent_messages`.`datetime`) AS MONTH, WEEK(`sent_messages`.`datetime`) AS WEEK,
DATE_FORMAT(`sent_messages`.`datetime`, '%Y-%m-%d') AS DATE
FROM `sent_messages`
INNER JOIN `received_messages` on `received_messages`.`uniqueid`=`sent_messages`.`originalID`
and `received_messages`.`msisdn`=`sent_messages`.`msisdn`
WHERE `sent_messages`.`datetime` >= '2016-12-12'
AND `sent_messages`.`originalID` = `received_messages`.`uniqueid`
AND `sent_messages`.`datetime` <= '2017-12-30'
AND `sent_messages`.`datetime` >= `received_messages`.`datetime`
AND `sent_messages`.`datetime` <= ( `received_messages`.`datetime` + INTERVAL 2 HOUR )
AND `sent_messages`.`type` = 'PAID'
GROUP BY WEEK
ORDER BY DATE ASC
因为我按WEEK
对其进行分组,我的结果是显示所有已发送,未发送等的总和,但不是每个msisdn。结果如下:
当我在msisdn
条款中添加GROUP BY
时,我不会按照我需要的方式得到结果。
我需要这样:
请帮助我编写优化查询,以便在过去8周内为每个msisdn获取这些结果,因为我被卡住了。
答案 0 :(得分:0)
WEEK(...)
在今年的第一天附近有问题。相反,您可以使用TO_DAYS
:
WHERE datetime > CURDATE() - INTERVAL 8 WEEK -- for the last 8 weeks
GROUP BY MOD(TO_DAYS(datetime), 7) -- group by week
这很简单,但它有一个错误。它只适用于今天是&#34;周&#34;的最后一天。如果日期%7落在所需的星期几。
WHERE datetime > CURDATE() - INTERVAL 9 WEEK -- for the last 8 weeks
GROUP BY MOD(TO_DAYS(datetime) - 3, 7) -- group by week
第一次修复错误 - 9周间隔将包括当前的部分周和8周前的部分周。 &#34; - 3&#34; (或任何数字的作品)将调整你的&#34;周&#34;从星期一或星期日或其他什么开始。
如果该列只有0或1个值,则 SUM(IF (sent_messages.delivered = 1,1,0 ))
可以缩短为SUM(delivered = 1)
甚至SUM(delivered)
。