SQL Server:在单个列上按部分分组

时间:2018-07-24 20:44:12

标签: sql sql-server group-by sum partial

当天早些时候已经问过类似的问题,解决方案使我想到了另一个问题(在示例之后):

    我有这些列,其中两个是数量。
  • 其中一个(LotQty)是一个总和,按Productid和Lot分组。
  • 另一个(SumQuantity)必须是仅按Productid分组的前者的和。

结果应如下所示:

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

如何更改选择以获取所需的结果?

2 个答案:

答案 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