如何在汇总另一列时返回列的最后一个值?

时间:2017-07-19 14:06:29

标签: sql sql-server-2008-r2

我有一个查询,会将消费数据汇总到某个日期时间@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(Employee列)中的最后一个值。因此,在下面的屏幕截图中,总回数应为1000,同时返回TG43499作为emp_num列的最后一个值。

enter image description here

1 个答案:

答案 0 :(得分: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
相关问题