通过不给我任何东西的组的SQL count(*)

时间:2018-10-07 12:31:24

标签: php mysql sql

我正在尝试编写一个查询,该查询将为我计算有多少条消息但没有运气。消息分为多个部分。同一封邮件的所有部分都具有相同的ID。

这是我的表格“ 消息

|     Text      |   ID   |   CreatorID  |   Status   |
   Hello Wo..      1234       Martin          OK
   rld! This..     1234       Martin          OK
   is a test!      1234       Martin          OK
   WELCOME p..     9999       Martin         Error
   eople to ..     9999       Martin         Error
   the party!      9999       Martin         Error

我想获得以下信息:

Total count of messages with CreatorID 'Martin' - 2 messages.
Total count of messages with CreatorID 'Martin' and Status 'Error' = 1 message.

我尝试了几种方法来完成此操作,但似乎都没有效果

SELECT COUNT(*) from messages WHERE CreatorID = 'Martin' GROUP BY ID (expecting 2)
SELECT COUNT(*) from messages WHERE CreatorID = 'Martin' AND status = 'Error' GROUP BY ID (expecting 1)

2 个答案:

答案 0 :(得分:1)

您需要使用Count(Distinct ...)而不是Group By

SELECT COUNT(Distinct ID) from messages WHERE CreatorID = 'Martin'
SELECT COUNT(Distinct ID) from messages WHERE CreatorID = 'Martin' AND status = 'Error'

您可以进一步使用条件聚合(利用If()函数)将其合并为单个查询:

SELECT COUNT(DISTINCT ID) AS total_messages, 
       COUNT(DISTINCT IF(status = 'Error', ID, NULL)) AS total_Error_messages 
FROM messages 
WHERE CreatorID = 'Martin'

答案 1 :(得分:1)

您可以在一个查询中同时执行这两个操作:

SELECT COUNT(DISTINCT m.id)  as num_messages,
       COUNT(DISTINCT CASE WHEN m.status = 'Error' THEN m.id END) as num_error_messages
FROM messages m
WHERE m.CreatorID = 'Martin';

如果每个CreatedID都需要这些,请使用GROUP BY

SELECT m.CreatorID,
       COUNT(DISTINCT m.id)  as num_messages,
       COUNT(DISTINCT CASE WHEN m.status = 'Error' THEN m.id END) as num_error_messages
FROM messages m
GROUP BY m.CreatorID;