sql-server - 分组和求和,使用非聚合标准来确定字段选择
问题描述
[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_no
、pipe_no
和cp_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
值总是正确的。
如何根据最大值选择所需HeaderID
的run_time
值?
解决方案
这不是聚合;这是过滤。使用相关子查询:
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
);
推荐阅读
- java - REST 请求 json Long 与原始 Long 不同
- kubernetes-helm - helm chart repo add 404 not found
- c# - C# WPF 窗口边距
- textbox - 文本框中只允许三个数值或字符
- python - 如何将数据中的数字放在条形图python上方
- python - argrelmin 的顺序:在两边指定不同的顺序
- laravel - 如何使用 JWT 在 Apiato 项目中编写生成令牌的函数?
- ssl - Tomcat 未在 8443 端口启动
- spring-data - 有没有办法在 Spring Data MongoDB 中不使用 @Version 注释来配置版本属性?
- algorithm - N级字符串压缩:解压缩算法