如何在调度SQL作业时获得Multiple select语句的单个输出

时间:2018-04-11 11:06:41

标签: sql sql-server ssms

我有一个员工表,其中employee ID前4个字段已修复但发布后根据位置发生变化。我需要获取报告以从该表中找到所有3个位置的最新记录。 我正在尝试运行3个select语句,在安排作业时,.csv file的输出有空行和some ------ lines。 如果我可以在没有任何行间距的单个文件中获得结果,那么有人可以提供帮助。

select top1 from Employee where ID like '42345%'  Orderby JoinedDate Desc
select top1 from Employee where ID like '42346%'  Orderby JoinedDate Desc
select top1 from Employee where ID like '42347%'  Orderby JoinedDate Desc

1 个答案:

答案 0 :(得分:0)

你似乎试图写这样的东西:

select e.*
from ((select top 1 e.*
       from Employee e
       where ID like '42345%' 
       Orderby JoinedDate Desc
      ) union all
      (select top 1 e.*
       from Employee e
       where ID like '42346%' 
       Orderby JoinedDate Desc
      ) union all
      (select top 1 e.*
       from Employee e
       where ID like '42347%' 
       Orderby JoinedDate Desc
      ) union all
     ) e;

也许更简单的方法是使用row_number()

select e.*
from (select e.*,
             row_number() over (partition by left(id, 5) order by joineddate desc) as seqnum
      from employee e
      where id like '4234[567]%'
     ) e
where seqnum = 1;