SQL Server:如何在另一个表中加入记录?

时间:2014-01-14 07:58:22

标签: sql sql-server join

我想显示员工的评估提交状态。

如果文件已提交,它将在Appraisal_Record表中添加一条记录。

如何编写显示所有员工所有评估期的SQL,即使他们没有提交评估(没有记录)。添加“状态”列以指示状态,“已提交”和“未提交”< - 如果[Appraisal_Record]表中没有记录

我想在sql语句中使用一个案例来添加一个列... CASE WHEN xxx然后“已提交”ELSE“Not_Submitted”作为状态

由于

以下是示例

表:StaffDB

+---+-----+
|SID|Name |
+---+-----+
|1  |Peter|
+---+-----+
|2  |John |
+---+-----+
|3  |Amy  |
+---+-----+

表:Appraisal Period

+--------+-----------------+
|PeriodID|PeriodDescription|
+--------+-----------------+
|1       |2012_Start_Term  |
+--------+-----------------+
|2       |2012_Mid_Term    |
+--------+-----------------+
|3       |2012_End_Term    |
+--------+-----------------+

表:Appraisal_Record

+--+---+--------+
|ID|SID|PeriodID|
+--+---+--------+
|1 |1  |1       |
+--+---+--------+
|2 |1  |2       |
+--+---+--------+
|3 |2  |3       |
+--+---+--------+

结果

+---+-----+--------+-----------------+-------------+
|SID|Name |PeriodID|PeriodDescription|Status       |
+---+-----+--------+-----------------+-------------+
|1  |Peter|1       |2012_Start_Term  |Submitted    |
+---+-----+--------+-----------------+-------------+
|1  |Peter|2       |2012_Mid_Term    |Submitted    |
+---+-----+--------+-----------------+-------------+
|1  |Peter|3       |2012_End_Term    |Not_Submitted|
+---+-----+--------+-----------------+-------------+
|2  |John |1       |2012_Start_Term  |Not_Submitted|
+---+-----+--------+-----------------+-------------+
|2  |John |2       |2012_Mid_Term    |Not_Submitted|
+---+-----+--------+-----------------+-------------+
|2  |John |3       |2012_End_Term    |Submitted    |
+---+-----+--------+-----------------+-------------+
|3  |Amy  |1       |2012_Start_Term  |Not_Submitted|
+---+-----+--------+-----------------+-------------+
|3  |Amy  |2       |2012_Mid_Term    |Not_Submitted|
+---+-----+--------+-----------------+-------------+
|3  |Amy  |3       |2012_End_Term    |Not_Submitted|
+---+-----+--------+-----------------+-------------+

感谢Kishore和Damien。

解决方案是:

select a.sid,a.name,b.periodid,b.perioddescription,
CASE WHEN c.ID IS NOT NULL then 'Submitted' ELSE 'Not_Submitted' as Status
from 
StaffDB a 
cross join 
[Appraisal Period] b
left join 
Appraisal_Record c on a.sid = c.sid and b.periodid =  c.periodid

1 个答案:

答案 0 :(得分:1)

您正在寻找(假设您的appraisal_record表中的状态列)

select a.sid,a.name,b.periodid,b.perioddescription,c.status
from 
StaffDB a 
cross join 
[Appraisal Period] b
left join 
Appraisal_Record c on a.sid = c.sid and b.periodid =  c.periodid