2017-07-19 29 views
0

我有一个查询汇总消费数据直到某个日期时间@end。但是,当行按trans_num(交易号)排序时,我还需要返回另一列Employee的最后一个值。我该怎么做呢?如何在求和另一列时返回列的最后一个值?

我到目前为止所尝试的是:我试过使用SELECT Top 1,但这不会给我每个项目的最后一名员工。该表具有trans_num作为主键,并且所有其他字段不是唯一的。我可以根据需要提供任何其他信息。

declare @start datetime2 = '7/17/17 05:00:00 AM' 
declare @end datetime2 = '7/18/17 05:00:00 AM' 
declare @job varchar(12) = 'W000017154' 
declare @suf int = 29 

select 

    t.item 
    , i.description 
    , sum(t.qty) as sumqty 
    , t.ref_num 
    , t.ref_line_suf 
    , (select top 1 

      t.emp_num 

     from 

      isw_lptrans as t 

     where 

      t.ref_num = @job 
      and t.ref_line_suf = @suf 
      and t.createdate between @start and @end 

     order by 

      trans_num desc 

    ) as lastemp 

from 

    isw_lptrans as t 
    inner join item as i on i.item = t.item 

where 

    t.trans_type = 'I' 
    and t.createdate between @start and @end 
    and t.ref_num = @job 
    and t.ref_line_suf = @suf 

group by 

    t.item 
    , i.description 
    , t.ref_num 
    , t.ref_line_suf 

行的截图:突出显示的行中指定的日期时间@end当最后一排。所以我需要总结qty列,但也返回emp_num(员工列)中的最后一个值。因此在下面的屏幕截图中,总数应为1000,而将TG43499作为emp_num列的最后一个值返回。

enter image description here

回答

1

您可以使用公用表表达式(CTE)和RANK函数,作为一个子查询将返回最后一个员工办理的每个项目?

此查询可能不完全正常工作,但它可以让你开始:

declare @start datetime2 = '7/17/17 05:00:00 AM' 
declare @end datetime2 = '7/18/17 05:00:00 AM' 
declare @job varchar(12) = 'W000017154' 
declare @suf int = 29 

with lastEmp as (
    select 
    t.emp_num 
    , t.item 
    , RANK() OVER (PARTITION BY t.item ORDER BY t.CreateDate DESC) AS rankValue 
    FROM isw_lptrans as t 
    WHERE t.ref_num = @job 
    and t.ref_line_suf = @suf 
    and t.createdate between @start and @end 
) 
select 
    t.item 
    , i.description 
    , sum(t.qty) as sumqty 
    , t.ref_num 
    , t.ref_line_suf 
    , le.emp_num lastEmployeeNum 
from 
    isw_lptrans as t 
inner join item as i on i.item = t.item 
inner join lastEmp le ON t.item = le.item AND le.rankValue = 1 
where 
    t.trans_type = 'I' 
    and t.createdate between @start and @end 
    and t.ref_num = @job 
    and t.ref_line_suf = @suf 
group by 
    t.item 
    , i.description 
    , t.ref_num 
    , t.ref_line_suf 
+1

啊,该死的,我希望为没有使用一个临时表或表表达式的解决方案。我无尽的乐观主义认为可以在同一个'SELECT'语句中做到这一切。但棘手的部分是,我没有在较新版本的SQL Server中存在的'LAST_VALUE()'函数。虽然谢谢! – DarthVoid

相关问题