首页 > 解决方案 > 分组和求和,使用非聚合标准来确定字段选择

问题描述

[MS SQL Server 2005 上的 T-SQL]

我正在尝试对 SQL 表中的行进行分组,但对如何选择某些列选项有要求,而不仅仅是基于通常的聚合函数。所以例如我有这张桌子:

HeaderID    mold_no     pipe_no cp_date         class total_pcs total_pss run_time
----------- ----------- ------- --------------- ----- --------- --------- ---------
113149      1603        A22     2019-10-17      35    216       1         9.08
113320      1603        A22     2019-10-17      35    1         0         0.00

我想按mold_nopipe_nocp_date分组class

但是,我想使用与 的HeaderID最大值相对应的值run_time

所以现在我有

select MIN(HeaderID) HeaderID, MAX(mold_no) mold_no, MAX(pipe_no) pipe_no, MAX(cp_date) cp_date,
    MAX(machine) machine, MAX(class) class, SUM(total_pcs) total_pcs, SUM(total_pss) total_pss 
from MyTable
group by cp_date, machine, mold_no, pipe_no, class 

但当然这不会真正起作用,因为我不能保证最低编号的HeaderID值总是正确的。

如何根据最大值选择所需HeaderIDrun_time值?

标签: sql-servertsqlaggregate-functions

解决方案


这不是聚合;这是过滤。使用相关子查询:

select t.*
from t
where t.run_time = (select max(t2.run_time)
                    from t t2
                    where t2.mold_no = t.mold_no and
                          t2.pipe_no = t.pipe_no and
                          t2.cp_date = t.cp_date and
                          t2.class = t.class
                  );

推荐阅读