SQL - 在一个查询上显示3个不同的计数

时间:2014-07-31 06:22:50

标签: mysql sql

这三个查询中的每一个都可以自行完成。但是,我希望所有三个COUNTS都显示在同一个查询中。除了WHERE语句中的细微变化外,它们是相同的。

/* Display Total Message Count */
SELECT People.Name, COUNT(Messages.SenderID) as "Total Messages Sent"
FROM Ballers.Messages JOIN Ballers.People
WHERE Messages.SenderID = People.ID
GROUP BY People.Name;

/* Display Text Message Count */
SELECT People.Name, COUNT(Messages.SenderID) as "Text Messages Sent"
FROM Ballers.Messages JOIN Ballers.People
WHERE Messages.SenderID = People.ID AND Type = "Text"
GROUP BY People.Name;

/* Display Picture Message Count */
SELECT People.Name, COUNT(Messages.SenderID) as "Picture Messages Sent"
FROM Ballers.Messages JOIN Ballers.People
WHERE Messages.SenderID = People.ID AND Type = "Picture"
GROUP BY People.Name;

我没有成功在同一个表上输出所有三个查询。我尝试了很多不同的东西,但都给了我错误。我对SQL很陌生,我还没有完全掌握一切是如何运作的。以下是失败代码的一个示例:

/* Display All Message Counts, 3 Queries In One */
SELECT 
People.Name, 
(COUNT(Messages.SenderID) as "Messages Sent"
WHERE Messages.SenderID = People.ID),
(COUNT(Messages.SenderID) as "Text Messages Sent"
WHERE Messages.SenderID = People.ID AND Type = "Text"), 
(COUNT(Messages.SenderID) as "Picture Messages Sent"
WHERE Messages.SenderID = People.ID AND Type = "Picture")
FROM Ballers.Messages JOIN Ballers.People
GROUP BY People.Name;

2 个答案:

答案 0 :(得分:1)

这未经过测试,但这些内容应该有效:

SELECT People.Name,
COUNT(*) AS AllMessages,
SUM(CASE WHEN Type='Text' THEN 1 ELSE 0 END) AS TextMessages,
SUM(CASE WHEN Type='Picture' THEN 1 ELSE 0 END) AS PictureMessages
FROM Ballers.Messages JOIN Ballers.People ON People.ID=Messages.SenderID
GROUP BY People.Name

答案 1 :(得分:0)

您可以尝试这样的事情:

SELECT
 `People1`.`Name`,
 COUNT(`Messages1`.`SenderId`) as `TotalMessagesSent`,
 COUNT(`Messages2`.`SenderId`) as `TextMessagesSent`,
 COUNT(`Messages3`.`SenderId`) as `PictureMessagesSent`
FROM
 `Messages` as `Messages1`
 JOIN `People` as `People1` ON (`Messages1`.`SenderId` = `People1`.`ID`),
 `Messages` as `Messages2`
 JOIN `People` as `People2` ON (`Messages2`.`SenderId` = `People2`.`ID` AND `Type`='Text'),
`Messages` as `Messages3`
 JOIN `People` as `People3` ON (`Messages3.`SenderId` = `People3`.`ID` AND `Type`='Pictures')
GROUP BY
 `People1`.`Name`

或者只从人员表中选择并加入消息:

SELECT
 `People`.`Name`,
 COUNT(`Messages1`.`SenderId`) as `TotalMessagesSent`,
 COUNT(`Messages2`.`SenderId`) as `TextMessagesSent`,
 COUNT(`Messages3`.`SenderId`) as `PictureMessagesSent`
FROM
 `People`
 JOIN `Messages` as `Messages1` ON (`Messages1`.`SenderId` = `People`.`ID`)
 JOIN `Messages` as `Messages2` ON (`Messages2`.`SenderId` = `People`.`ID` AND `Type`='Text')
 JOIN `Messages` as `Messages3` ON (`Messages3.`SenderId` = `People`.`ID` AND `Type`='Pictures')
GROUP BY
 `People`.`Name`

也许它没有完整,也没有经过测试。