基于子查询数量的结果集

时间:2019-03-11 17:11:44

标签: sql sql-server

我有两个要合并的查询;基本上,第一个查询可以找出已分发了多少特定产品的项目

SELECT 
    T0.SOPOrderReturnLineID,
    T1.Quantity AS 'QtyDespatched',
    T0.LineQuantity As 'OrderQty',
    T1.SopLinkId AS 'DespatchSopLinkId',
    T1.ItemCode 
FROM
    SOPOrderReturnLine AS T0
LEFT JOIN 
    DespatchedItems AS T1 ON T0.SOPOrderReturnLineID = T1.SopLinkId
WHERE
    T1.SopLinkId IS NOT NULL AND
    T1.ItemCode = 'GSNOBAS60GW'
GROUP BY 
    T1.SopLinkId, T0.SOPOrderReturnLineID, 
    T1.Quantity, T0.LineQuantity, T1.ItemCode

这是两个查询的示例结果集

ql

第二个查询通过求和,直到OrderQty与已完成的3个匹配为止,我不希望这些项目出现在上面的结果集中,从而找出总共制造了多少个项目。到目前为止,这是怎么做的?。

SELECT 
    SUM(CONVERT(INT, T1.Quantity))
FROM 
    SOPOrderReturnLine AS T0
LEFT JOIN 
    DespatchedItems AS T1 ON T0.SOPOrderReturnLineID = T1.SopLinkId
WHERE
    T1.SopLinkId IS NOT NULL AND
    T1.ItemCode = 'GSNOBAS60GW'

1 个答案:

答案 0 :(得分:1)

可以肯定这只是一个典型的聚合查询。这样的事情。注意,我将您的别名更改为与表相关的名称。通用别名的使用确实具有挑战性。 https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-table-aliases-like-a-b-c-or-t1-t2-t3

SELECT 
    ORL.SOPOrderReturnLineID,
    SUM(DI.Quantity) AS 'QtyDespatched',
    ORL.LineQuantity As 'OrderQty',
    DI.SopLinkId AS 'DespatchSopLinkId',
    DI.ItemCode 
FROM
    SOPOrderReturnLine AS ORL
LEFT JOIN 
    Fuel_DespatchedItems AS DI ON ORL.SOPOrderReturnLineID = DI.SopLinkId
WHERE
    DI.SopLinkId IS NOT NULL AND
    DI.ItemCode = 'GSNOBAS60GW'
GROUP BY 
    DI.SopLinkId
    , ORL.SOPOrderReturnLineID
    , ORL.LineQuantity
    , DI.ItemCode

如果要过滤聚合,请使用HAVING子句。

只需在分组依据之后添加HAVING。

SELECT 
    ORL.SOPOrderReturnLineID,
    SUM(DI.Quantity) AS 'QtyDespatched',
    ORL.LineQuantity As 'OrderQty',
    DI.SopLinkId AS 'DespatchSopLinkId',
    DI.ItemCode 
FROM
    SOPOrderReturnLine AS ORL
LEFT JOIN 
    Fuel_DespatchedItems AS DI ON ORL.SOPOrderReturnLineID = DI.SopLinkId
WHERE
    DI.SopLinkId IS NOT NULL AND
    DI.ItemCode = 'GSNOBAS60GW'
GROUP BY 
    DI.SopLinkId
    , ORL.SOPOrderReturnLineID
    , ORL.LineQuantity
    , DI.ItemCode
HAVING SUM(DI.Quantity) < ORL.LineQuantity