2010-03-27 66 views
6

我試圖在我的視圖中獲取COUNT的結果作爲列。 請參閱下面的查詢的那種我想要的東西的演示(這只是用於演示目的)視圖中的SQL計數列爲

SELECT 
    ProductID, 
    Name, 
    Description, 
    Price, 
    (SELECT COUNT(*) FROM ord WHERE ord.ProductID = prod.ProductID) AS TotalNumberOfOrders 

FROM tblProducts prod 
LEFT JOIN tblOrders ord ON prod.ProductID = ord.ProductID 

這顯然是不工作...但我不知道做什麼的正確方法這將是?

我使用SQL Server

回答

7

,如果你刪除的加入您的查詢將實際工作 - 它不實際使用,這將導致inner select subquery內的ORD表與ORD表衝突,你已經加入到:

SELECT 
    ProductID, 
    Name, 
    Description, 
    Price, 
    (SELECT COUNT(*) FROM ord WHERE ord.ProductID = prod.ProductID) AS TotalNumberOfOrders 
FROM tblProducts prod 

或者,你可以實際使用的連接表的結合Group By

SELECT 
    ProductID, 
    Name, 
    Description, 
    Price, 
    COUNT(ord.ProductID) AS TotalNumberOfOrders 
FROM tblProducts prod 
LEFT JOIN tblOrders ord ON prod.ProductID = ord.ProductID 
GROUP BY 
    ProductID, 
    Name, 
    Description, 
    Price 
4

試試這個:

SELECT 
    ProductID, 
    Name, 
    Description, 
    Price, 
count(*) as totalnumberoforders 
FROM tblProducts prod 
LEFT JOIN tblOrders ord ON prod.ProductID = ord.ProductID 
group by 
    ProductID, 
    Name, 
    Description, 
    Price 
1

如果你只對已訂購的產品有興趣,你可以簡單地代替LEFT OUTER JOIN與INNER操作JOIN:

SELECT 
    prod.ProductID, 
    prod.Name, 
    prod.Description, 
    prod. Price, 
    COUNT(*) AS TotalNumberOfOrders 
FROM tblProducts prod 
INNER JOIN tblOrders ord ON prod.ProductID = ord.ProductID 
0

這將工作:

SELECT 
    ProductID, 
    Name, 
    Description, 
    Price, 
    COUNT(ord.ProductId) AS TotalNumberOfOrders 
FROM tblProducts prod 
LEFT JOIN tblOrders ord 
ON prod.ProductID = ord.ProductID 
GROUP BY 
    ProductID, 
    Name, 
    Description, 
    Price 

「COUNT(ord.ProductId)」子句可確保如果未找到任何訂單,則TotalNumberOfOrders將等於零。

[稍後編輯:我忘了GROUP BY子句。 Doh!]