2我有两张桌子
一个logs.emails:
EmailNum EmployeeID, Emailcontent, EmailReceivers ,is_read
1 1 , "sasa" , "sas@google.com" ,1
2 1 , "sasa" , "sas@google.com" ,0
3 2 , "sasa" , "sas@google.com" ,0
4 2 , "sasa" , "sas@google.com" ,0
5 2 , "sasa" , "sas@google.com" ,0
和Employees.user
id, FirstName, LastNAme
1 , "John" , "Brown"
2 , "Jack" , "James"
我想要的输出:
FirstName,LastName,NumOfUnreadEmails
约翰,布朗,1 杰克,詹姆斯,3岁
我的尝试(但它没有返回第一行所需的输出,即“John,Brown,1”):
SELECT
*, count(EmployeeID) as NumEmails
FROM
logs.emails a
inner join
Employees.user b on a.EmployeeID=b.id
group by
EmployeeID
having
a.is_read='0'
感谢您的帮助
答案 0 :(得分:3)
您应在此处指定WHERE
子句,而不是使用HAVING
,因为您尝试在进行任何聚合之前过滤掉is_read=0
的记录。
此外,为了只获取所需的字段,请不要使用*
。只需指定所需的字段即可。
SELECT
b.FirstName, b.LastName, COUNT(a.EmailNum)
FROM
logs.emails a
inner join
Employees.user b on a.EmployeeID=b.id
where
a.is_read='0'
group by
b.id
答案 1 :(得分:1)
尝试这种方式:
SELECT b.FirstName, b.LastName,
sum( case
when a.is_read=0 than 1
else 0
end ) as NumOfUnreadEmails
FROM logs.emails a
inner join Employees.user b on a.EmployeeID=b.id
group by b.FirstName, b.LastName
答案 2 :(得分:1)
这将返回所有员工,包括根本没有任何电子邮件的员工。如果您只想显示包含未读电子邮件的邮件,可以将LEFT JOIN
更改为INNER JOIN
。
SELECT
u.FirstName,
u.LastName,
COUNT(e.EmployeeID) AS NumOfUnreadEmails
FROM
Employees.user u
LEFT JOIN logs.emails e ON e.EmployeeID = u.id AND e.is_read = 0
GROUP BY
u.id