T-SQL查询以下表定义

时间:2015-08-10 11:06:29

标签: sql-server sql-server-2008

我的数据库中有四个表,您可以在下面看到包含示例数据的示例。

表1 tbl_ActivityName

id  empId   ActivityName    
---------------------------------------
1    20      30_20
2    21      30_21
3    22      30_22

4    20      31_20
5    21      31_21
6    22      31_22

7    20      32_20
8    21      33_21
9    22      34_22

表2 tbl_Monday

id  empId   ActivityName    Plan    Actual
-------------------------------------------------------------------
1    20     30_20            1.1    1.1
2    20     30_20            1.2    1.1
3    21     30_21            1.3    1.2

表3 tbl_Tuesday

id  empId   ActivityName    Plan    Actual
------------------------------------
1    22       31_22          1.2    1.3
2    21       31_21          1.3    1.2
3    22       32_22          1.1    1.3

表4 tbl_Wednesday

id  empId   ActivityName    Plan    Actual
-------------------------------------------------------------------
1    22       31_22          1.2    1.3
2    22       31_22          1.3    1.2
3    20       30_20          1.1    1.3

我试着为他们写一个查询,如下:

select 
    a.empid, a.activityname,
    b.plan, b.actual,
    c.plan, c.actual,
    d.plan, d.actual 
from 
    tbl_activityname a,
    tbl_moday b,
    tb_tuesday c,
    tbl_wednesday d 
where 
    a.activityname = '30_20'
    and b.activityname = '30_20'
    and c.activityname = '30_20'

然而,这并没有回复我的预期结果。这是我预期的结果:

预期结果forempid = 20 and Activityname = 30_20 from tbl_ActivityName

activityName    empid   Monday_Plan Mondat_Actual   Tuesday_Plan    Tuesday_Actual  Wednesday_Plan  Wednesday_Actual
--------------------------------------------------------------------------------------------------------------------
30_20            20      1.1           1.1          -             -       1.1         1.3

预期结果forempid = 22 and Activityname = 31_22 from tbl_ActivityName

activityName    empid   Monday_Plan Mondat_Actual   Tuesday_Plan    Tuesday_Actual  Wednesday_Plan  Wednesday_Actual
--------------------------------------------------------------------------------------------------------------------
31_22               22          -           -          1.2            1.3               1.2            1.3
31_22               22          -           -           -              -                1.3            1.2

为什么我的查询没有获得这些预期结果?

1 个答案:

答案 0 :(得分:0)

您需要使用OUTER JOIN,以便在其中一个表中没有匹配数据时仍然可以获得结果:

select 
    a.empid, a.activityname,
    b.plan, b.actual,
    c.plan, c.actual,
    d.plan, d.actual 
from tbl_activityname a
left outer join    tbl_monday b
  on a.activityname=b.activityname
left outer join    tb_tuesday c
  on a.activityname=c.activityname
left outer join     tbl_wednesday d 
  on a.activityname=d.activityname
where 
    a.activityname = '30_20'