I’m using SQL Server 2005. I get this error:
*The multi-part identifier “ms.MOP_desc” could not be bound.*
I tested each of the two select queries and they worked fine individually, but I got the error when I union those queries. Can I anyone tell me what went wrong with this query? Thank you.
SELECT SUM(Amount) AS TotalAmount, ms.MOP_desc
FROM
(
SELECT SUM(hd.delivery_value) AS Amount, ms.MOP_desc
FROM TRANSACTION_HEADER AS th
INNER JOIN TRANSACTION_DETAIL AS td
ON th.transaction_number = td.transaction_number
LEFT JOIN hose_delivery hd
ON td.delivery_id = hd.delivery_id
LEFT JOIN product pr
ON pr.product_id = td.product_id
INNER JOIN MOP_Setting AS ms
ON hd.MOP_ID = ms.MOP_ID
WHERE hd.delivery_value > 0
AND (th.USER_PERIOD_ID IN (13))
AND (hd.MOP_ID IN (1))
AND hd.Cleared_By != '0'
GROUP BY ms.MOP_desc
UNION ALL
SELECT SUM(td.quantity * td.price_sold) AS Amount, ms.MOP_desc
FROM TRANSACTION_HEADER AS th
INNER JOIN TRANSACTION_DETAIL AS td
ON th.transaction_number = td.transaction_number
INNER JOIN MOP_Setting AS ms
ON th.MOP_ID = ms.MOP_ID
WHERE (th.USER_PERIOD_ID IN (13))
AND (th.MOP_ID IN (1))
GROUP BY ms.MOP_desc
)t
Because the result from the
UNIONed query is a rowset that you’ve given the aliastto – themsalias is no longer applicable:If this really is a second
SUMstep here, you’ll need a outerGROUP BYclause also.