1
請幫助我查詢。我在DBMS方面很弱。查詢處理SQL Server
我有有一些行如下
pkParentId FKProductId Name
1 5 P1
2 5 P2
3 3 P3
表TBLParent
,我有另一個表TBLChild
是由它的孩子
pkId fkParentId ChildName
1 1 C1
2 1 c2
3 2 c1
現在的,問題是,我想父記錄和計數的子女根據productId
。
例如:我想
select
TBLParent.pkParentId, TBLParent.FKProductId,
TBLParent.Name,
count of its children
where
TBLParent.FKProductId = 5
我試過這樣
Select
count(TBLChild.pkId) AS total,
TBLChild.fkParentId
from
TBLChild
group by
TBLChild.fkParentId
,但我怎麼能附上父表的記錄,這個算不算?
這將給我數,但我將如何附加父記錄與此計數。我的意思是說輸出將是
pkParentId Name Count
1 P1 2
2 P2 1
請幫忙請幫助請幫忙嗎?
但主席先生,我想通過fkParentId記錄不pkParentId像上面的查詢選擇P.pkParentId ,P.Name ,COUNT(*)FROM tblParent P INNER JOIN tblChild C ON P. pkParentId = C.fkParentId WHERE P.fkParentId = @yourValueHere GROUP BY P.pkParentId,P.Name – Prince 2013-04-24 14:10:06
在上面的查詢中,fkParentId和pkParentId將相等。查詢中的「INNER JOIN」部分對你來說是什麼。根據您的問題中的示例輸出,此查詢將爲您提供您正在尋找的內容。 – Aushin 2013-04-24 14:13:47
好的先生根據你的情況,如果我把@ yourValueHere = 5,它會返回我所需的結果。很抱歉再次打擾你。但是我最後的回答讓我感到困惑。 – Prince 2013-04-24 14:25:00