MSSQL按总和列跳过分组
我找不到关于我正在尝试做什么的相关标题和描述。所以我希望你能从这个例子中理解MSSQL按总和列跳过分组,sql,sql-server,group-by,sum,Sql,Sql Server,Group By,Sum,我找不到关于我正在尝试做什么的相关标题和描述。所以我希望你能从这个例子中理解 我有这两列,其中两列是数量 其中一个(LotQty)为总和 另一个(SumQuantity)必须是前者的总和 其余的(Productid和Lot)保持按分组 结果应该如下所示: SumQuantity Productid LotQty Lot 512 40652 256.000000 2020-12-20 512
- 我有这两列,其中两列是数量李>
- 其中一个(LotQty)为总和
- 另一个(SumQuantity)必须是前者的总和
- 其余的(Productid和Lot)保持按分组
SumQuantity Productid LotQty Lot
512 40652 256.000000 2020-12-20
512 40652 256.000000 2020-12-21
即SumQuantity=总和(LotQuantity)。
我应该如何更改我的选择(如下)以创建该效果
select 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
结果是:
Productid LotQty Lot
40652 256.000000 2020-12-20
40652 256.000000 2020-12-21
样本表
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
您似乎想要一个窗口功能:
select s.productid, sum(s.cuquantity) as LotQty, la.Value as Lot,
sum(sum(s.cuquantity)) over () as totalLogQty
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
10倍。那很快。实际上可能有用……我承认我不知道如何求和。现在我必须测试它编辑:测试它,只有一个小东西-只有当where子句看起来像这样时它才起作用:“where l.receiptid=5950195和productid=40652”否则TotalogQTY列的结果是2048,而不是512(即链接到receiptid的3个productid和一个空行(从我的左连接))。所以基本上-它就像我希望的那样工作(没有组员:),但它有一个价格。。。不管怎样,还是10倍。我将把它标记为解决方案,并尝试从这里找出答案。