2014-01-23 44 views
2

試圖用COALESCE執行此代碼以將數據組合在一起。執行時,我看到這個錯誤SQL代碼出錯

消息207,級別16,狀態1,行11 無效的列名稱'OrderID'。 消息209,級別16,狀態1,行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 
+0

根據你使用的(MySQL和SQL的服務器,Oracle等) –

+0

SELECT c.CustomerID的SQL請標籤的問題, c.FirstName, c.LastName, COALESCE(c.OrderIDCnt,0), COALESCE(c.SKUCnt,0), COALESCE(c.OrderTotal,0) FROM顧客爲c 左加入(選擇o .CustomerID, SUM(o.OrderTotal)AS OrderTotal, COUNT(o.OrderedProductSKU)AS SKUCnt, COUNT(o.OrderID)AS OrderIDCnt FROM訂單鄰 內部聯接Orders_ShoppingCart作爲osc.OrderNumber OSC = o.OrderNumber 和osc.CustomerID = o.CustomerID GROUP BY o.CustomerID )ORD ON ord.CustomerID = c.CustomerID – Gayathri

回答

2

的錯誤意味着SQL語法分析程序無法唯一解決unqialified名CustomerID。有兩個候選有:

  • Customer表的CustomerID領域,
  • ord子查詢的CustomerID領域。

儘管兩者必須匹配,因爲您的連接條件要求ord.CustomerID = c.CustomerID,查詢解析器不能爲您任意選擇一個。因此,您需要通過在CustomerID前面指定cord來手動消除歧義,或者在子查詢中爲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

+0

感謝。重命名該字段可解決一個問題。另一個仍然是消息207,級別16,狀態1,行11 無效的列名稱'訂單ID'。 – Dean

+0

@ DeanFraser-Phillips我看到了 - Orders_ShoppingCart表上還有'OrderID',對吧?我也爲此添加了歧義 - 請參閱編輯。 – dasblinkenlight

3

嘗試使用c.CustomerId或ord.CustomerId

0

您在表Orders和Customer中具有名爲customerId的字段,並且您不指定要在select子句中包含哪個字段。

在這種情況下,你應該總是在格式alias.field鍵入場