mysql - 按日期范围和分组依据的sum字段

时间:2014-09-22 15:50:31

标签: mysql sql

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)

有人能帮助我吗?

4 个答案:

答案 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

一些注意事项:

  • 您可以将状态过滤器移动到WHERE子句以简化操作。确保您在此列上有索引
  • 您不应该像使用DATE(sent_time)一样在where子句中使用计算值进行比较,因为这会阻止使用索引。您可以简单地使用00:00:0023: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