当天早些时候已经问过类似的问题,解决方案使我想到了另一个问题(在示例之后):
结果应如下所示:
SumQuantity Productid LotQty Lot
----------------------------------------------------
512 40652 256.000000 2020-12-20
512 40652 256.000000 2020-12-21
1024 40661 512.000000 2019-12-19
1024 40661 512.000000 2019-12-20
512 40710 256.000000 2021-03-03
512 40710 256.000000 2021-04-04
即SumQuantity = sum(LotQty)按产品ID分组,而sum(LotQty)按产品ID和批次分组。
select
sum(sum(s.cuquantity)) over () SumQuantity,
s.productid, sum(s.cuquantity) LotQty, la.Value Lot
from
log l
left join
logstock s on s.logid = l.id
left join
Logstockattributes la on la.LogStockID = s.id and la.AttributeID = 10
where
l.receiptid = 5950195
group by
productid, la.value
结果是:
SumQuantity Productid LotQty Lot
---------------------------------------------------
2048 40652 256.000000 2020-12-20
2048 40652 256.000000 2020-12-21
2048 40661 512.000000 2019-12-19
2048 40661 512.000000 2019-12-20
2048 40710 256.000000 2021-03-03
2048 40710 256.000000 2021-04-04
样品表
Logid Productid Cuquantity Lot
-----------------------------------------------------
1 40652 256.000000 2020-12-20
2 40652 255.000000 2020-12-21
3 40652 1.000000 2020-12-21
4 40661 512.000000 2019-12-19
5 40661 512.000000 2019-12-20
6 40710 256.000000 2021-03-03
7 40710 255.000000 2021-04-04
8 40710 1.000000 2021-04-04
如何更改选择以获取所需的结果?
答案 0 :(得分:1)
我认为您只需要partition by
:
select sum(sum(s.cuquantity)) over (partition by productid) as SumQuantity,
s.productid, sum(s.cuquantity) as LotQty, la.Value as Lot
from log l left join
logstock s
on s.logid = l.id left join
Logstockattributes la
on la.LogStockID = s.id and la.AttributeID = 10
where l.receiptid = 5950195
group by productid,la.value
答案 1 :(得分:0)
您只需要添加分区,然后删除多余的SUM
。本质上,您需要窗口函数而不是完全聚合方法,以便您可以返回行级别的详细信息。
select distinct
SumQuantity = sum(Cuquantity) over (partition by Productid),
LotQty = sum(Cuquantity) over (partition by Productid, Lot),
Productid,
Lot
from log l
left join logstock s on s.logid=l.id
left join Logstockattributes la on la.LogStockID=s.id and la.AttributeID=10
where l.receiptid=5950195
la.value