2014-09-18 134 views
0

我有兩個表。一個持有員工,一個持有項目。員工表有一個主鍵,項目有一個外鍵來標識哪個員工在哪個項目上工作。我需要編寫一個查詢來返回員工的名字和姓氏,但僅限於那些處理兩個或更多項目的員工。這是我到目前爲止有:我需要幫助創建一個查詢sql

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 

我讀過使用計數,但一直沒能實現與加盟伯爵已經停留了一段時間。

回答

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; 
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