sql查询组合两个具有相同id的记录

时间:2011-08-02 10:10:59

标签: sql-server

我创建了一个查询来计算PO数量和SO数量。问题是,对于SO数量,我得到两行,用于具有不同SO数量的相同产品。我想要做的是为相同的产品添加SO数量,并在数据库中将其显示为单行。请告知。

以下是我写的查询:

SELECT DISTINCT products.ProductCode,
                products.ProductName,
                pe.stockreorderqty,
                pe.stocklowqtyalarm,
                products.StockStatus,
                pe.lastpo_qty,
                pe.lastpo_date,
                pe.vendor_price,
                Sum(PO_Items.POI_Quantity) - Sum(PO_Items.POI_QtyReceived) AS OutstandingPOQty,
                orderdetails.Quantity as outstandingsoqty
FROM Products INNER JOIN Products_Extended pe WITH (NOLOCK) ON products.ProductID = pe.ProductID 
LEFT JOIN PO_Items ON products.ProductCode = PO_Items.POI_ProductCode
LEFT JOIN orderdetails 
INNER JOIN orders ON orderdetails.OrderID = orders.OrderID  ON orderdetails.productcode = products.productcode 
    AND orders.OrderStatus <>'Cancelled' 
    AND orders.OrderStatus <>'Shipped'
    AND orders.OrderStatus <>'Returned'
GROUP BY products.ProductCode, products.ProductName, pe.stockreorderqty,
         pe.stocklowqtyalarm, products.StockStatus, pe.lastpo_qty,
         pe.lastpo_date, pe.vendor_price, orderdetails.Quantity

我获得的查询输出如下:

productcode
productname
stockreorderqty
stocklowqtyalarm
stockstatus
lastpo_qty
lastpo_date
vendor_price
outstandingpoqty
outstandingsoqty
10195
Carclo 19° Frosted 20mm Lens - No Holder
0
5
120
300
06/16/11 09:32 PM
1.05
0
50

Carclo 19° Frosted 20mm Lens - No Holder
0
5
120
300
06/16/11 09:32 PM
1.05
0
56

在上面的输出中,产品代码相同,只有优点不同。我想添加outstandingsoqty并将两行显示为一行。  对于相同的产品代码,它们与不同的开放式销售订单具有不同的优异性。

您可以在以下链接中检查图像以进行输出: http://qedlr.fhmto.servertrust.com/v/vspfiles/assets/images/queryresult.png

1 个答案:

答案 0 :(得分:0)

这有简单的方法。不要使用Group by您期望大结果集的位置,它会使您的查询变慢,而是使用子查询。

这样做:

SELECT DISTINCT [OTHER Fields], 
(SELECT Sum(PO_Items.POI_Quantity) - Sum(PO_Items.POI_QtyReceived) FROM PO_Items WHERE PO_Items.POI_ProductCode = products.ProductCode) as OutstandingPOQty,
(SELECT Sum(det1.Quantity) FROM orderdetails AS det1 WHERE det1.productcode =products.productcode and det1.OrderID=orders.OrderID) as outstandingsoqty
FROM Products 
INNER JOIN Products_Extended pe WITH (NOLOCK) ON products.ProductID = pe.ProductID 
LEFT JOIN orderdetails INNER JOIN orders ON orderdetails.OrderID = orders.OrderID ON orderdetails.productcode = products.productcode 
and orders.OrderStatus <>'Cancelled' and orders.OrderStatus <>'Shipped' and orders.OrderStatus <>'Returned' 

会很快。希望它有所帮助。