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