SQL不是我的专长,但是,如何编写一个SQL查询,从两个不同的记录中取值并将它们放在一行中?例如,我对此EmployeeId
进行了查询,我需要具体来自Vacation_Type
列的输出值,用于2016-07-01
上的调整(如果存在)和来自日期的转发值{ {1}}(每位员工都有)?期望的输出将是:
2016-08-01
并非每个员工都有一个调整记录,当他们超过病假上限时,他们会有一个调整......并且不是每个人都超过了上限。谢谢!
答案 0 :(得分:2)
select
EV.EmployeeID,
EV.Vacation_Kind,
stuff( ( select ', ' + convert(varchar(30), EV1.Value) from EmployeeVacations EV1
where EV1.EmployeeID = EV.EmployeeID and EV1.Vacation_Kind = EV.Vacation_Kind
and EV1.VacationType in ('Adjust','Forward') and EV1.CreationDate IN (EV.CreationDate, dateadd(month, datediff(month, 0, dateadd(month, 1, EV.CreationDate)), 0))
for xml path('')
), 1, 1, '')
from
EmployeeVacations EV
where
EV.EmployeeID = 26 and EV.Vacation_Kind = 'SL'and VacationType = 'Adjust'
group by
EV.EmployeeID, EV.Vacation_Kind, EV.CreationDate
答案 1 :(得分:1)
由于不保证“调整”记录存在,您可以使用LEFT OUTER JOIN。以下查询所有员工,但如果您真的只需要员工26 ......
,则可以取消注释这两行patterns.lst