SQL代码出错

时间:2014-01-23 16:25:57

标签: mysql

尝试使用COALESCE执行此代码以将数据分组在一起。执行时我看到此错误

Msg 207,Level 16,State 1,Line 11 列名称'OrderID'无效。 Msg 209,Level 16,State 1,Line 1 不明确的列名称'CustomerID'。

SELECT CustomerID,
FirstName,
LastName,
COALESCE(OrderIDCnt,0),
COALESCE(SKUCnt,0),
COALESCE(OrderTotal,0)
FROM Customer as c
left join (SELECT o.CustomerID,
       SUM(OrderTotal) AS OrderTotal,
       COUNT(OrderedProductSKU) AS SKUCnt,
       COUNT(OrderID) AS OrderIDCnt
       FROM Orders as o
       inner join Orders_ShoppingCart as osc
       on osc.OrderNumber=o.OrderNumber
       and osc.CustomerID=o.CustomerID
       GROUP BY o.CustomerID
      )ord
ON ord.CustomerID = c.CustomerID

3 个答案:

答案 0 :(得分:3)

尝试使用c.CustomerId或ord.CustomerId

答案 1 :(得分:2)

错误意味着SQL解析器无法唯一地解析未加密码的名称CustomerID。那里有两个候选人:

  • CustomerID表的Customer字段和
  • CustomerID子查询的ord字段。

虽然两者必须匹配,因为您的连接条件需要ord.CustomerID = c.CustomerID,查询解析器不能随意为您选择一个。因此,您需要通过在c前指定ordCustomerID或在子查询中为CustomerID选择其他名称来手动消除歧义。

第一种方法:

SELECT c.CustomerID, -- Add c. in front of CustomerID
FirstName,
LastName,
COALESCE(OrderIDCnt,0),
COALESCE(SKUCnt,0),
COALESCE(OrderTotal,0)
FROM Customer as c
left join (SELECT o.CustomerID,
       SUM(OrderTotal) AS OrderTotal,
       COUNT(OrderedProductSKU) AS SKUCnt,
       COUNT(o.OrderID) AS OrderIDCnt -- Disambiguated OrderID
       FROM Orders as o
       inner join Orders_ShoppingCart as osc
       on osc.OrderNumber=o.OrderNumber
       and osc.CustomerID=o.CustomerID
       GROUP BY o.CustomerID
      )ord
ON ord.CustomerID = c.CustomerID

第二种方法:

SELECT CustomerID,
FirstName,
LastName,
COALESCE(OrderIDCnt,0),
COALESCE(SKUCnt,0),
COALESCE(OrderTotal,0)
FROM Customer as c
left join (SELECT o.CustomerID as OrderCustomerID, -- add an alias
       SUM(OrderTotal) AS OrderTotal,
       COUNT(OrderedProductSKU) AS SKUCnt,
       COUNT(o.OrderID) AS OrderIDCnt -- Disambiguated OrderID
       FROM Orders as o
       inner join Orders_ShoppingCart as osc
       on osc.OrderNumber=o.OrderNumber
       and osc.CustomerID=o.CustomerID
       GROUP BY o.CustomerID
      )ord
ON ord.OrderCustomerID = c.CustomerID -- Rename the field

修改:消除歧义OrderID

答案 2 :(得分:0)

您在表Orders和Customer中有一个名为customerId的字段,并且您没有在select子句中指定要包含的字段。

在这种情况下,您始终应以alias.field

格式键入字段