我如何编写sql来恢复它

时间:2017-09-22 14:20:22

标签: tsql

我需要从表A中带回不同的行。我需要从表b和c中获取员工300。他可以看到siteid 1和2以及EmployingActivityId 10和50以及克制这些记录的最有效方法是什么

Table A
id   Employeeid   SiteId   EmployingActivityId
1       123          1        10
2       124          2        10
3       125          3       30
4       126         2        40
5    127            5        50
6    128            2        60


Table b
employeeid    SiteID
300                1
300                2
400                2


table C
employeeid    EmployingActivityId
300               10
300               50
400               20

我知道这不对,但是......

select distinct id, Employeeid from tableA as a
inner join
    (select siteID from tableb (where employee = 300) on tableb.siteID = tableA.siteid
inner join
    (select siteID from tablec (where employee = 300) on tablec.EmployingActivityId = tableA.EmployingActivityId

我需要从表A中带回来

id     Employeeid
1    123
2    124
5    127
6    128 

1 个答案:

答案 0 :(得分:0)

我会做这样的事情:

declare @a as table(
    id int
    ,employeeId int
    ,siteId int
    ,employeeActivityId int
)

declare @b as table(
    employeeID int
    ,siteId int
)

declare @c as table(
    employeeid int
    ,employeeActivitatyID int
)

insert into @a values (1,123,1,10)
insert into @a values (2,124,2,10)
insert into @a values (3,125,3,30)
insert into @a values (4,126,2,40)
insert into @a values (5,127,5,50)
insert into @a values (6,128,2,60)

insert into @b values (300,1)
insert into @b values (300,2)
insert into @b values (400,2)

insert into @c values (300,10)
insert into @c values (300,50)
insert into @c values (400,20)


select distinct id, a.employeeid
from @a a
left join @b b
    on a.siteId = b.siteId
left join @c c
    on a.employeeActivityId = c.employeeActivitatyID
where 300 in (b.employeeID, c.employeeId)