我需要帮助在sql上创建一个查询

时间:2014-09-18 19:44:52

标签: sql

我有两张桌子。一个持有员工,另一个持有项目。 Employee表具有主键,项目具有外键,用于标识哪个员工正在处理哪个项目。我需要编写一个查询,该查询将返回员工的名字和姓氏,但仅限于处理两个或更多项目的员工。这就是我到目前为止所做的:

create table employee
(
employeeId int not null identity(1,1) primary key,
firstName varChar(25) not null,
lastName varChar(25) not null,
gender varChar(1) not null,
dob date not null,
ssn varChar(9) not null,
)

insert into employee
 values 
    ('Peter','Smith','m','1979-08-25','123112233'),
    ('Juan','Doe','m','1985-05-22','435678907'),
    ('Rafael','Perez','m','1979-03-22','754984568'

create table projects
(
projectId int identity(1,1) primary key not null,
description varChar(100) not null,
status varChar(10) not null,
startDate date not null,
projectedEndDate date not null,
manager int foreign key references employee(employeeId)

insert into projects
values ('this project will improve the power on certain devices','active','2014-09-12','2015-0101','1'),
   ('this project will improve the user interface','active','2014-09-12','2015-01-01','1'),
   ('this project will improve the load time','active','2014-09-12','2015-01-01','2'),
   ('this project will implement stronger security','active','2014-09-12','2015-01-01','2')

   select firstname +' '+ lastname as fullname 
   from projects 
   inner join employee 
   on employee.employeeid = projects.manager 

返回

Peter Smith
Peter Smith
Juan Doe
Juan Doe
Rafael Perez

我已经读过使用点数,但是还没有能够实现计数的加入,已经坚持了一段时间。

2 个答案:

答案 0 :(得分:1)

您需要group byhaving子句:

select firstname +' '+ lastname as fullname 
from projects inner join
     employee 
     on employee.employeeid = projects.manager 
group by firstname +' '+ lastname
having count(*) >= 2;

答案 1 :(得分:0)

你总是可以包装SQL:

SELECT fullname FROM (
   select firstname +' '+ lastname as fullname 
   from projects 
   inner join employee 
   on employee.employeeid = projects.manager ) t
GROUP BY fullname
HAVING COUNT(distinct projectId) > 1