我正在使用SQL Server 2005.我收到此错误:
*无法绑定多部分标识符“ms.MOP_desc”。*
我测试了两个选择查询中的每个查询并且它们单独运行良好,但是当我联合这些查询时我得到了错误。我可以告诉我这个查询出了什么问题吗?谢谢。
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
答案 0 :(得分:2)
由于UNION
ed查询的结果是您已将别名t
指定给的行集,因此ms
别名不再适用:
SELECT SUM(Amount) AS TotalAmount, t.MOP_desc
FROM
(
...
)t
如果这确实是第二个SUM
步骤,那么您还需要一个外部GROUP BY
子句。
答案 1 :(得分:1)
当您从子选择而不是表中进行选择时,子选择中的列名称不会暴露给外部选择
使用
SELECT SUM(Amount) AS TotalAmount, mop
FROM
(
SELECT SUM(hd.delivery_value) AS Amount, ms.MOP_desc as mop
FROM TRANSACTION_HEADER AS th
INNER JOIN TRANSACTION_DETAIL AS td
...