基于聚合和连接的SQL查询

时间:2016-08-29 23:46:06

标签: sql sql-server stored-procedures

我是SQL新手,我试图通过执行聚合和连接函数来连接两个表。我正在使用OrderdetailsPurchaseOrderDetails表来加入OrderID

我想比较OrderDetails表格中的数量总和与基于特定PurchaseOrderDetails的{​​{1}}表和sum(PurchaseOrderDetails.quantity) != sum(OrderDetails.quantity)中的数量总和,并根据它们加入在orderID

我有以下两个表:

orderID表格设计

OrderDetails

SELECT TOP 1000 [lineID] ,[orderID] ,[itemNumber] ,[itemDesc] ,[qty] ,[price] ,[priceType] ,[contract] ,[supplierPartID] ,[uom] ,[classDomain] ,[classValue] ,[comments] ,[shipping] ,[tax] ,[reqDeliveryDate] ,[fillInfo] ,[invoiceID] ,[Version] ,[productid] ,[eta] ,[lineOrderID] FROM [bfdb].[dbo].[OrderDetails] 表设计是:

PurchaseOrderDetails

我尝试了以下查询但得到的结果不正确。假设SELECT TOP 1000 [podID] ,[poID] ,[distPN] ,[mfrID] ,[itemNumber] ,[itemName] ,[qty] ,[price] ,[invoiceID] ,[orderID] ,[itemReceived] ,[qtyReceived] ,[distConf] ,[distFillStatus] ,[distLastUpdate] ,[distTracking] ,[distFillDesc] ,[Version] ,[productid] ,[lineOrderID] FROM [bfdb].[dbo].[PurchaseOrderDetails] 表中有1行,OrderDetails中有2行,则加入后PurchaseOrderDetails的总和变为双倍。与OrderDetails表中的1行相同,如果我在PurchaseOrderDetails表中有超过1行

OrderDetails

以下是我的数据的快照

PurchaseOrderDetails

OrderDetails

2 个答案:

答案 0 :(得分:1)

您需要先分别sum这两个表中的每一个的orderid数量,然后加入。试试这个:

select od.orderID, pod.qty as Totalqty, od.qty as od_qty
from (
    select orderid, sum(pod.qty) as qty
    from PurchaseOrderDetails
    group by orderid
) pod
inner join (
    select orderid, sum(pod.qty) as qty
    from OrderDetails
    group by orderid
) od on od.orderid = pod.orderid

答案 1 :(得分:0)

您只需将AND条件更改为WHERE子句,请尝试以下代码:

SELECT od.orderID, SUM(pod.qty) as Totalqty, SUM(od.qty) as od_qty FROM PurchaseOrderDetails pod INNER JOIN OrderDetails od ON od.orderID = pod.orderID WHERE pod.orderID = 15506 GROUP BY od.orderID