[英]SQL query frouping - how does the following work?
I am trying to get a Cutting Group within cutting list(CutGroup).我正在尝试在切割列表(CutGroup)中获得一个切割组。
Master Table - Tab1:主表 - Tab1:
enter image description here在此处输入图像描述
I am looking sum (Qty) in each group (ID, GroupSLN, MaxLen, Len, Reminder) and keep each group structure(Group) as it is.我正在查看每个组(ID、GroupSLN、MaxLen、Len、Reminder)中的总和(数量)并保持每个组结构(组)不变。 This is code which I've tried so far:这是我到目前为止尝试过的代码:
SELECT ID, GroupSLN , MaxLen, Len, Reminder ,Sum(Qty), max(SLN) AS SLN
FROM Prd300_OPT
GROUP BY BarID, Bar, Length, Reminder, BarSizeID, SessionID ,Cuts
ORDER BY SLN
The id and maxlen seem the columns of importance. id 和 maxlen 似乎是重要的列。 Using a sub query I can downfill the maxlen and use that to join back to the main table in a sub query to get the sum of qty over id and maxlen.使用子查询,我可以向下填充 maxlen 并使用它在子查询中加入主表,以获得 id 和 maxlen 上的 qty 总和。
drop table if exists t;
create table t
(id int,maxlen int,len int, reminder int,qty int,sln int auto_increment primary key);
insert into t (id,maxlen,len,reminder,qty) values
(1,100,1000,null,1),(1,null,1000,1100,null),
(2,200,2000,null,1),(2,null,2000,2100,null),
(2,200,2000,null,1),(2,null,2000,2100,null),
(2,200,2000,null,1),(2,null,2000,2100,null);
select id,maxlen,len,reminder,
case when s.qty is not null then
(select sum(qty) from t where t.id = s.id and t.maxlen = s.lastmaxlen)
end as qty
from
(
select distinct
id,maxlen,len,reminder,qty,
case when maxlen is null then
(select
maxlen from t t1 where t1.sln < t.sln and t1.maxlen > 0 order by sln desc limit 1)
else maxlen
end as lastmaxlen
from t
) s
;
+------+--------+------+----------+------+
| id | maxlen | len | reminder | qty |
+------+--------+------+----------+------+
| 1 | 100 | 1000 | NULL | 1 |
| 1 | NULL | 1000 | 1100 | NULL |
| 2 | 200 | 2000 | NULL | 3 |
| 2 | NULL | 2000 | 2100 | NULL |
+------+--------+------+----------+------+
4 rows in set (0.00 sec)
Notice the use of the distinct clause to dedupe in the sub query.请注意在子查询中使用 distinct 子句进行重复数据删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.