0

我正在使用 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
4

2 回答 2

2

因为UNIONed 查询的结果是您为其赋予别名的行集t-ms别名不再适用:

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

如果这真的是SUM这里的第二步,那么您GROUP BY还需要一个外部子句。

于 2013-01-04T08:54:16.100 回答
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 
...
于 2013-01-04T08:51:51.453 回答