合并ContainerID行并添加数量

时间:2019-07-17 13:46:18

标签: sql sql-server

我想合并容器ID,日期并添加数量。此查询显示项目级别的数据。我希望它在订单级别打印数据并加总“数量”列。

我可以使用excel和数据透视表合并行,但是当我运行报表超过3个月时,我用完了excel中的行,因此将其分成较小的块并添加结果。乏味。必须有一种更简单的方法。

我得到的是什么

OrderDate   ContainerID Qty
2019-06-03  104922434   1
2019-06-03  104922434   1
2019-06-01  104934958   1
2019-06-01  104934958   1
2019-06-01  104934958   1

我想要什么:

OrderDate   ContainerID Qty
2019-06-03  104922434   2
2019-06-01  104934958   3

我当前的查询:

select     

convert(date,oh.ShipTime) as 'OrderDate',
p.ContainerID,
cc.Qty

from dmhost.tblOrderHeader oh

join dmhost.tblContainer c on oh.OrderHeaderID = c.OrderHeaderID
join dmhost.tblPackage p on c.ContainerID = p.ContainerID
join dmhost.tblContainerContents cc on c.ContainerID = cc.ContainerID
join dmhost.tblItemMaster im on im.ItemMasterID = cc.ItemMasterID

where (oh.ShipTime between '06/1/2019' and '07/1/2019')
and (BusinessUnitCode like '03'or BusinessUnitCode like '04')
and cc.Qty <> 0

order by p.ContainerID

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用SUMGROUP BY

select     

convert(date,oh.ShipTime) as 'OrderDate',
p.ContainerID,
SUM(cc.Qty) Qty

from dmhost.tblOrderHeader oh

join dmhost.tblContainer c on oh.OrderHeaderID = c.OrderHeaderID
join dmhost.tblPackage p on c.ContainerID = p.ContainerID
join dmhost.tblContainerContents cc on c.ContainerID = cc.ContainerID
join dmhost.tblItemMaster im on im.ItemMasterID = cc.ItemMasterID

where (oh.ShipTime between '06/1/2019' and '07/1/2019')
and (BusinessUnitCode like '03'or BusinessUnitCode like '04')
and cc.Qty <> 0

group by
    convert(date,oh.ShipTime),
    p.ContainerID

order by ContainerID