我有两个单独运行良好的查询,我需要将它们组合起来。一个查询使用“Group By”,另一个查询使用子查询。
第一个查询:
SELECT
LH.AISLE AS "Aisle",
LH.DSP_LOCN AS "Location",
WI.TC_LPN_ID AS "iLPN",
IC.ITEM_NAME AS "Item",
WI.ON_HAND_QTY AS "Qty",
(SELECT
SUM(OLI.ORDER_QTY)
FROM
ORDERS O,
ORDER_LINE_ITEM OLI
WHERE
O.ORDER_ID = OLI.ORDER_ID
AND
O.DO_STATUS = 110
AND
OLI.ITEM_ID = IC.ITEM_ID) AS "Released Qty"
FROM
WM_INVENTORY WI,
LOCN_HDR LH,
ITEM_CBO IC
WHERE
WI.LOCATION_ID = LH.LOCN_ID
AND
WI.ITEM_ID = IC.ITEM_ID
AND
LH.ZONE = 'R'
AND
LH.LVL = '20'
ORDER BY
LH.DSP_LOCN;
第二个查询:
SELECT
LH.AISLE AS "Aisle",
LH.DSP_LOCN AS "Location",
WI.TC_LPN_ID AS "iLPN",
IC.ITEM_NAME AS "Item",
WI.ON_HAND_QTY AS "Qty",
SUM (WI2.ON_HAND_QTY) AS "CP Qty"
FROM
LOCN_HDR LH,
WM_INVENTORY WI,
ITEM_CBO IC
LEFT JOIN WM_INVENTORY WI2
ON (WI2.ITEM_ID = IC.ITEM_ID AND WI2.LOCN_CLASS = 'C')
WHERE
WI.LOCATION_ID = LH.LOCN_ID
AND
WI.ITEM_ID = IC.ITEM_ID
AND
LH.ZONE = 'R'
AND
LH.LVL = '20'
GROUP BY
LH.AISLE,
LH.DSP_LOCN,
WI.TC_LPN_ID,
IC.ITEM_NAME,
WI.ON_HAND_QTY
ORDER BY
LH.DSP_LOCN;
我不知道如何将子查询添加到组中,以便它们一起工作。
如果两个查询都正常工作并返回您需要的数据,一个简单的选择是使用
UNION
集合运算符。
简化
select ... from ... where ... --> the 1st query
union all
select ... from ... where ... --> the 2nd query
使用您的代码:
SELECT
LH.AISLE AS "Aisle",
LH.DSP_LOCN AS "Location",
WI.TC_LPN_ID AS "iLPN",
IC.ITEM_NAME AS "Item",
WI.ON_HAND_QTY AS "Qty",
(SELECT
SUM(OLI.ORDER_QTY)
FROM
ORDERS O,
ORDER_LINE_ITEM OLI
WHERE
O.ORDER_ID = OLI.ORDER_ID
AND
O.DO_STATUS = 110
AND
OLI.ITEM_ID = IC.ITEM_ID) AS "Released Qty"
FROM
WM_INVENTORY WI,
LOCN_HDR LH,
ITEM_CBO IC
WHERE
WI.LOCATION_ID = LH.LOCN_ID
AND
WI.ITEM_ID = IC.ITEM_ID
AND
LH.ZONE = 'R'
AND
LH.LVL = '20'
--
UNION ALL
--
SELECT
LH.AISLE AS "Aisle",
LH.DSP_LOCN AS "Location",
WI.TC_LPN_ID AS "iLPN",
IC.ITEM_NAME AS "Item",
WI.ON_HAND_QTY AS "Qty",
SUM (WI2.ON_HAND_QTY) AS "CP Qty"
FROM
LOCN_HDR LH,
WM_INVENTORY WI,
ITEM_CBO IC
LEFT JOIN WM_INVENTORY WI2
ON (WI2.ITEM_ID = IC.ITEM_ID AND WI2.LOCN_CLASS = 'C')
WHERE
WI.LOCATION_ID = LH.LOCN_ID
AND
WI.ITEM_ID = IC.ITEM_ID
AND
LH.ZONE = 'R'
AND
LH.LVL = '20'
GROUP BY
LH.AISLE,
LH.DSP_LOCN,
WI.TC_LPN_ID,
IC.ITEM_NAME,
WI.ON_HAND_QTY
ORDER BY 2;
请注意,两个查询都必须返回相同数量的列(显然,它们确实如此),这些列必须在数据类型中匹配(无法确定,因为我没有您的表及其描述,但您应该知道) .
从
order by
子句开始:它仅出现在整个代码的末尾(这就是为什么在第一个查询之后没有 order by
)。