可以使用公共表表达式(
CTE
此查询可能无法完全正常工作,但可以让您开始:
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