Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Join 4 tables

Author  Topic 

fm88
Starting Member

18 Posts

Posted - 2008-07-23 : 05:11:13
Hi there,I have 4 tables

sample data from tables are

employee
employeeid name team
1 x team1
2 y team2


project est
projectid employeeid hoursest
1 1 6
2 5 10


projectact
projectid employeeid hoursact
1 1 6
1 1 10
1 2 7
etc...

ProjTable
projectid projectname
1 proj1
2 proj2

is it able in a single query to select all projects,and the employees worked on that project with respective hours,example..

projid emplname team hoursest hoursact
1 x team1 6 16
1 y team2 0 7
2 x team1 9 0
etc...

..thanks

RyanRandall
Master Smack Fu Yak Hacker

1074 Posts

Posted - 2008-07-23 : 05:58:38
Here's something to get us started...

--sample data
declare @employee table (employeeid int, name varchar(10), team varchar(10))
insert @employee
select 1, 'x', 'team1'
union all select 2, 'y', 'team2'
union all select 5, 'z', 'team3'

declare @projectest table (projectid int, employeeid int, hoursest int)
insert @projectest
select 1, 1, 6
union all select 2, 5, 10

declare @projectact table (projectid int, employeeid int, hoursact int)
insert @projectact
select 1, 1, 6
union all select 1, 1, 10
union all select 1, 2, 7

declare @ProjTable table (projectid int, projectname varchar(10))
insert @ProjTable
select 1, 'proj1'
union all select 2, 'proj2'

--query
select a.projectid, b.name as emplname, b.team, c.projectname,
isnull(d.hoursest, 0) as hoursest, isnull(e.hoursact, 0) as hoursact
from
(select projectid, employeeid from @projectest union
select projectid, employeeid from @projectact) a
inner join @employee b on a.employeeid = b.employeeid
inner join @ProjTable c on a.projectid = c.projectid
left outer join (select projectid, employeeid, sum(hoursest) as hoursest
from @projectest group by projectid, employeeid)
d on a.employeeid = d.employeeid and a.projectid = d.projectid
left outer join (select projectid, employeeid, sum(hoursact) as hoursact
from @projectact group by projectid, employeeid)
e on a.employeeid = e.employeeid and a.projectid = e.projectid


Ryan Randall
Solutions are easy. Understanding the problem, now, that's the hard part.
Go to Top of Page

fm88
Starting Member

18 Posts

Posted - 2008-07-24 : 01:00:45
Thanks..it worked perfectly
Go to Top of Page
   

- Advertisement -