2013-01-04 42 views
0

我使用的是SQL Server 2005中我得到這個錯誤:「多部分組成的標識符不能被束縛」的錯誤

*The multi-part identifier "ms.MOP_desc" could not be bound.*

我測試了上述2個選擇查詢和他們工作得很好分別,但我當我結合這些查詢時出現錯誤。我可以告訴我這個查詢出了什麼問題嗎?謝謝。

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 

回答

2

因爲從UNION ED結果查詢是一個行集,您已將別名t設置爲 - ms別名不再適用:

SELECT SUM(Amount) AS TotalAmount, t.MOP_desc 
FROM 
(
... 
)t 

如果這真的是第二步SUM步驟,您還需要一個外部GROUP BY子句。

+0

謝謝你的解釋。它確實有幫助。 – ixora

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 
... 
+1

這就是爲什麼你沒有得到金額這個錯誤的原因。您已經在查詢中爲該列指定了一個列名稱。 – LuigiEdlCarno

+2

「來自子選擇的列名不暴露給外部選擇」是公然*不*真*。您必須爲任何其他*未命名*列(例如'SUM')指定名稱,但列名稱保留 –

+0

它的工作原理。感謝您的幫助和解釋。 – ixora

相關問題