我想显示items
表的所有记录。但有些数量需要是负值。
BEGIN
SET @ItemId1 = (SELECT ItemId FROM items);
SELECT
SUM(ROUND(Quantity))
FROM (
SELECT
COALESCE(SUM(od.Quantity),0) as Quantity
FROM sts as T1
LEFT JOIN orderset_details as od
ON T1.OrdersetId = od.OrdersetId
WHERE od.ItemId = @ItemId1
UNION ALL
SELECT
COALESCE(SUM(od.Quantity),0) as Quantity
FROM drs as T2
LEFT JOIN orderset_details as od
ON T2.OrdersetId = od.OrdersetId
WHERE od.ItemId = @ItemId1
UNION ALL
SELECT
COALESCE(
SUM(
IF(r.AddsToStock = '1', od.Quantity, 0 - od.Quantity)
),0
) as Quantity
FROM stockadjustment as T3
LEFT JOIN reason as r
ON r.ReasonId = T3.ReasonId
LEFT JOIN orderset_details as od
ON T3.OrdersetId = od.OrdersetId
WHERE od.ItemId = @ItemId1
UNION ALL
SELECT
COALESCE(
SUM(
IF(T4.OrdersetId = od.OrdersetId, 0 - od.Quantity, -1 * od.Quantity)
),0
) as Quantity
FROM issueslip as T4
LEFT JOIN orderset_details as od
ON T4.OrdersetId = od.OrdersetId
WHERE od.ItemId = @ItemId1
UNION ALL
SELECT
COALESCE(
SUM(
IF(T4.OrdersetId = od.OrdersetId, 0 - od.Quantity, -1 * od.Quantity)
),0
) as Quantity
FROM invoice as T4
LEFT JOIN orderset_details as od
ON T4.OrdersetId = od.OrdersetId
WHERE od.ItemId = @ItemId1
) as t;
END
此代码出现错误MySQL said: #1242 -Subquery returns more than 1 row
。
我想要显示每件商品的所有数量。这就是为什么我有@ ItemId1得到所有ItemId from items
。我怎么能这样做?
答案 0 :(得分:1)
您应该按ItemId进行分组。 试试这个
SELECT
ItemId, SUM(ROUND(Quantity))
FROM (
SELECT
od.ItemId, COALESCE(SUM(od.Quantity),0) as Quantity
FROM sts as T1
LEFT JOIN orderset_details as od
ON T1.OrdersetId = od.OrdersetId
-- WHERE od.ItemId = @ItemId1
GROUP BY od.ItemId
UNION ALL
SELECT
od.ItemId, COALESCE(SUM(od.Quantity),0) as Quantity
FROM drs as T2
LEFT JOIN orderset_details as od
ON T2.OrdersetId = od.OrdersetId
--WHERE od.ItemId = @ItemId1
GROUP BY od.ItemId
UNION ALL
SELECT
od.ItemId,
COALESCE(
SUM(
IF(r.AddsToStock = '1', od.Quantity, 0 - od.Quantity)
),0
) as Quantity
FROM stockadjustment as T3
LEFT JOIN reason as r
ON r.ReasonId = T3.ReasonId
LEFT JOIN orderset_details as od
ON T3.OrdersetId = od.OrdersetId
--WHERE od.ItemId = @ItemId1
GROUP BY od.ItemId
UNION ALL
SELECT
od.ItemId,
COALESCE(
SUM(
IF(T4.OrdersetId = od.OrdersetId, 0 - od.Quantity, -1 * od.Quantity)
),0
) as Quantity
FROM issueslip as T4
LEFT JOIN orderset_details as od
ON T4.OrdersetId = od.OrdersetId
--WHERE od.ItemId = @ItemId1
GROUP BY od.ItemId
UNION ALL
SELECT
od.ItemId
COALESCE(
SUM(
IF(T4.OrdersetId = od.OrdersetId, 0 - od.Quantity, -1 * od.Quantity)
),0
) as Quantity
FROM invoice as T4
LEFT JOIN orderset_details as od
ON T4.OrdersetId = od.OrdersetId
--WHERE od.ItemId = @ItemId1
GROUP BY od.ItemId
) as t
GROUP BY ItemId;