0

2 我有两张桌子

一个日志。电子邮件:

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"

我想要的输出:

名字,姓氏,未读电子邮件数
John , Brown , 1
Jack , James ,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'

感谢您的帮助

4

3 回答 3

3

您应该在此处指定一个WHERE子句而不是 using 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 
于 2013-07-23T17:57:08.323 回答
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 
于 2013-07-23T17:53:52.310 回答
1

这将返回所有员工,包括根本没有任何电子邮件的员工。如果您只想显示那些确实有未读电子邮件的人,您可以更改LEFT JOININNER 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
于 2013-07-23T17:57:22.307 回答