id | sent_time | status | campaignId |
---+-------------------+--------+------------+
1 |2013-12-26 00:00:00| sent | 12 |
---+-------------------+--------+------------+
2 |2013-12-26 00:00:00| sent | 12 |
---+-------------------+--------+------------+
3 |2013-12-26 00:00:00| sent | 11 |
---+-------------------+--------+------------+
4 |2018-10-21 00:00:00| draft | 13 |
---+-------------------+--------+------------+
5 |2018-10-21 00:00:00| draft | 14 |
---+-------------------+--------+------------+
6 |2018-10-21 00:00:00| draft | 14 |
---+-------------------+--------+------------+
我想在 sent_time 字段范围内显示日期之间的数据,并将获得相同“campaignId”的“已发送”状态相加 这是我的疑问:
SELECT DATE(sent_time) AS date_sent_time, SUM(status='sent') AS total_sent_status
FROM sms_table WHERE (DATE(sent_time) BETWEEN 2014-08-26 AND 2014-09-30)
AND campaignId = 12 GROUP BY DATE(sent_time)
有人能帮助我吗?
答案 0 :(得分:2)
试试这个:
SELECT
DATE(sent_time) AS sent_date,
COUNT(id) AS total_sent_status
FROM sms_table
WHERE
status = 'sent'
AND campaignID = 12
AND sent_time BETWEEN '2014-08-26 00:00:00' AND '2014-09-30 23:59:59'
GROUP BY sent_date
一些注意事项:
DATE(sent_time)
一样在where子句中使用计算值进行比较,因为这会阻止使用索引。您可以简单地使用00:00:00
和23:59:59
解决此问题,或者更好的是,如果您的sent_time
字段确实具有00:00:00
的所有时间成分,如示例数据所示,只需将它作为日期字段。答案 1 :(得分:1)
您可以将status='sent'
上的条件移动到WHERE子句,并将COUNT(id)
添加到SELECT中,如下所示:
SELECT DATE(sent_time) AS date_sent_time, COUNT(id) AS total_sent_status
FROM sms_table
WHERE sent_time BETWEEN '2014-08-26 00:00:00' AND '2014-09-30 23:59:59'
AND campaignId = 12
AND status = 'sent'
GROUP BY date_sent_time
您确实不应该在where子句中使用函数,因为这可能会阻止MySQL使用索引。另请注意,您可以在GROUP BY子句中使用别名。
这是sqlfiddle。
答案 2 :(得分:0)
您可以对我的多列进行分组......
... GROUP BY DATE(sent_time), campaignId
包括细分。
或者作为完整的查询...
SELECT DATE(sent_time) AS date_sent_time, campaignId, SUM(status='sent') AS total_sent_status
FROM sms_table WHERE (DATE(sent_time) BETWEEN 2014-08-26 AND 2014-09-30)
GROUP BY DATE(sent_time), campaignId
答案 3 :(得分:0)
此查询将为您提供2014-08-26和2014-09-30之间发生的CampaignID 12状态为“已发送”的记录数
SELECT
DATE(sent_time) AS date_sent_time,
COUNT(status) AS total_sent_status
FROM sms_table
WHERE
DATE(sent_time) BETWEEN '2014-08-26' AND '2014-09-30' AND
campaignId = 12 AND
status = 'Sent'
GROUP BY sent_time