2013-10-15 21 views
0

這似乎是這樣一個簡單的查詢運行,但我不能得到它的工作,我開始重新思考爲什麼我選擇瞭解決這個項目。計數表中給出相應的ID記錄

我想查找一個id是否相同的表中有多少條記錄。例如,

select productid, productgroup, shelflvl, shelfaisle, Count(Shelfaisle) AS totalaisles 
from productlocation 
Where productid= productid AND productgroup = 'canned' 
Group By productid, productgroup, shelflvl, shelfaisle 

具有相同id的產品可以位於不同的過道和不同的shelflvl上。我所要做的就是查看一個產品有多少通道,而且我不能讓我的生活正常工作。

任何幫助表示感謝你!

回答

0

我假設一個產品不能屬於多個productgroup秒。

刪除ShelfaisleGROUP BY因爲這是你要數數。

此外,COUNT(DISTINCT Shelfaisle)將防止重複(如果適用)。

最後,你不需要productid=productid條件,這顯然總是產生true

切割長話短說:

select 
    productid, productgroup, shelflvl, Count(distinct Shelfaisle) AS totalaisles 
from productlocation 
Where productgroup = 'canned' 
Group By productid, productgroup, shelflvl 
+0

明顯是我的問題。我真的不知道爲什麼這會起作用,但它確實如此。謝謝 –

0

由列不組你想聚集:

select productid, productgroup, Count(Shelfaisle) AS totalaisles 
from productlocation 
Where productid=productid AND productgroup = 'canned' 
Group By productid, productgroup 
+0

甚至當我這樣做,我仍然得到1返回的值的每一行,多行的ProductID。在頂部,我有一個productid顯示3次,每行totalaisles值爲1,我需要它顯示產品id一次,並且總過道值爲3 –

0

如何:

select productid, productgroup, Count(shelfaisle) AS totalaisles 
from productlocation 
Where productid= productid AND productgroup = 'canned' 
Group By productid,productgroup 

您是通過添加額外的列組,這意味着你可以」將產品隔離爲數字。當您只需要產品和shelfaisle時,您正在計算特定貨架級上特定行的產品。

0

這會工作:

SELECT productid, shelflvl, MIN(productgroup) AS productgroup, 
    COUNT(Shelfaisle) AS totalaisles 
FROM productlocation 
WHERE productgroup = 'canned' 
GROUP BY productid, shelflvl 
ORDER BY productid;