日期:2014-05-18  浏览次数:20678 次

如何写这个sql语句?谢谢
有两张表:
员工表(id,name,department)

id name department
001 小王 部门A
002 小张 部门B
003 小明 部门C



培训表(id,person_id,train)
id person_id train time
001 001 培训A 2007.02.23
002 001 培训B 2009.04.21
003 002 培训A 2010.04.02
004 002 培训C 2011.01.06


求近三年(2009,2010,2011)没有参加过“培训A”的人,结果是“小王,小明”。

这个sql怎么写了?很久不用了,忘记了差不多,求指点,谢谢!

------解决方案--------------------
SQL code

Declare @Employ Table(
    ID         Varchar(20) Primary Key,
    Name        Varchar(20),
    Department    Varchar(20)    
)

Declare @Train Table(
    ID         Varchar(20) Primary Key,
    person_id    Varchar(20),
    train    Varchar(20),    
    time    DateTime
)

Insert Into @Employ
Select '001', '小王', '部门A'
Union Select '002', '小张', '部门B'
Union Select '003', '小明', '部门C'

Insert Into @Train
Select '001', '001', '培训A', '2007.02.23'
Union Select '002', '001', '培训B', '2009.04.21'
Union Select '003', '002', '培训A', '2010.04.02'
Union Select '004', '002', '培训C', '2011.01.06'

Select * From @Employ
Where ID Not In (Select person_id From @Train 
Where Year(time) In ('2009','2010','2011') And Train = '培训A')

------解决方案--------------------

declare @ret varchar(500)

select @ret =isnull( @ret+',','')+name from ta a where not exists(select 1 from tb b where year(time) in( 2011,2010,2009) and b.person_id = a.id and b.train = '培训A')
 
select @ret
------解决方案--------------------
Select [员工表].id ,[员工表].name ,[员工表].department ,[培训表].train ,[培训表].time
From [员工表] left join [培训表] on [员工表].id = [培训表].person_id
Where [员工表].ID Not In (Select person_id From [培训表] 
Where Year(time) In ('2009','2010','2011') And Train = '培训A')

结果:
001 小王 部门A 培训A 2007-02-23 00:00:00.000
001 小王 部门A 培训B 2009-04-21 00:00:00.000
003 小明 部门C NULL NULL