我有这个SQL工作正常
SELECT COUNT(*) AS total, e.FirstName, e.LastName
FROM [Messages] AS m
INNER JOIN Employees AS e ON m.SenderId = e.UserId
GROUP BY e.EmployeeId, e.FirstName, e.LastName
但我希望还有完整的未读消息作为列。
如何在SQL中实现这一目标?
SELECT
COUNT(*) AS total,
COUNT(where m.isRead = false) AS totalUnreadMessages,
e.FirstName, e.LastName
FROM
[Messages] AS m
INNER JOIN
Employees AS e ON m.SenderId = e.UserId
GROUP BY
e.EmployeeId, e.FirstName, e.LastName
答案 0 :(得分:5)
你几乎就在那里,使用case
表达式进行条件计数:
SELECT Count(*) as total,Count(case when m.isRead = false then 1 end) as totalUnreadMessage,
e.FirstName,e.LastName
FROM [Messages] as m
inner join Employees as e on m.SenderId=e.UserId
group by e.EmployeeId, e.FirstName,e.LastName
答案 1 :(得分:3)
我会把它写成:
AttributeError: 'unicode' object has no attribute 'p'
答案 2 :(得分:0)
您可以计算它们,然后使用原始选择加入它们:
SELECT Count(*) as total,tbNotRead.NotReadNumber AS totalUnreadMessage, e.FirstName,e.LastName
FROM [Messages] as m
INNER JOIN Employees as e ON m.SenderId=e.UserId
LEFT OUTER JOIN
(
SELECT m.Sender, COUNT(*) NotReadNumber
FROM [Messages] msgs
WHERE m.isRead = FALSE
GROUP BY m.Sender
)tbNotRead
ON tbNotRear.Sender = m.sender
GROUP BY e.EmployeeId, e.FirstName,e.LastName, tbNotRead.NotReadNumber