代码之家  ›  专栏  ›  技术社区  ›  DarthVoid

如何在对另一列求和时返回该列的最后一个值?

  •  0
  • DarthVoid  · 技术社区  · 8 年前

    @end 但是,当行按排序时,我还需要返回另一列Employee的最后一个值 trans_num (交易编号)。我该怎么做?

    我试着使用 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
    

    行的屏幕截图: @结束 指定了日期时间。所以我需要求和 qty 列,然后还返回中的最后一个值 emp_num (员工列)。因此,在下面的屏幕截图中,返回时的总数量应为1000 TG43499 电磁脉冲数

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  1
  •   Vince I Muthu    8 年前

    可以使用公共表表达式( 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