2017-10-21 65 views
0

我試圖將COUNT鏈接到SQL Server數據庫中幾個表的特定值。在這種情況下,表格只通過相關性共享值。我正在返回我想要的值,但是COUNT正在計算給定項目中的所有內容,而不僅僅是與其工作項目相關的項目。SQL:通過多個表將計數鏈接到特定值

 SELECT 
      [d].[Id] 
      ,COUNT([t].[ItemId]) AS ItemCount 
      ,[d].[ItemName] 
     FROM 
      [dbo].[Project_Map] [rm] WITH (NOLOCK) 
     INNER JOIN 
      [dbo].[WorkProjects] [r] WITH (NOLOCK) 
      ON [r].[DomainId] = [rm].[DomainId] 
      AND [r].[ProjectId] = [rm].[ProjectId] 
      AND [r].[ReleaseId] = [rm].[ReleaseId] 
     INNER JOIN 
      [dbo].[Items] [d] WITH (NOLOCK) 
      ON [d].[DomainId] = [r].[DomainId] 
      AND [d].[ProjectId] = [r].[ProjectId] 
      AND [d].[ReleaseId] = [r].[ReleaseId] 
     INNER JOIN [dbo].[Projects] [p] with (NOLOCK) 
     ON r.DomainId = p.DomainId 
     AND r.ProjectId = p.ProjectId 
     INNER JOIN [dbo].[Tests] [t] with (NOLOCK) 
     ON p.DomainId = t.DomainId 
     AND p.ProjectId = t.ProjectId 
     INNER JOIN 
     (
      SELECT [Id], MAX([LastModifiedDate]) AS MostRecent 
      FROM Items 
      Group By [Id] 
     ) AS updatedItem 
     ON updatedItem.Id = d.Id 
     INNER JOIN 
      [dbo].[WorkItemStates] [ds] WITH (NOLOCK) 
      ON [ds].[ItemStateName] = [d].[ItemStatus] 
     WHERE 
      d.Id = 111111 
      AND d.UserCategory Like 'SOMESTRING' 
     GROUP BY d.Id, d.ItemName 

退貨:在這種情況下的計數應該是1,但它返回整個項目的數量。

  ID COUNT ITEMNAME 
      86 5169 SOME NAME 
      173 5169 SOME NAME 
      170 5169 SOME NAME 

我錯過了某處的連接嗎?

+1

樣本數據和期望的結果真的有幫助。 –

+0

很難分辨出這麼多的信息,但從經驗來看,我可以告訴你,你可能不會錯過一個連接,但是在連接的一個ON條件中缺少一個子句...... – Noxthron

回答

1

當前,您的計數正在計算所有JOIN實例,而不僅僅是明顯的級記錄。考慮把你項目單位層面加入到聚集查詢加入,包括在外部分組計數字段:

具體變化:

INNER JOIN [dbo].[Tests] [t] with (NOLOCK) 
     ON p.DomainId = t.DomainId 
     AND p.ProjectId = t.ProjectId 

分爲:

INNER JOIN 
    (SELECT t.DomaindId, t.ProjectId, Count(*) As ItemCount 
    FROM [dbo].[Tests] t 
    GROUP BY t.DomaindId, t.ProjectId) agg 
ON p.DomainId = agg.DomainId 
AND p.ProjectId = agg.ProjectId 

然後是外部查詢結構變爲:

SELECT 
    [d].[Id] 
    ,agg.ItemCount 
    ,[d].[ItemName] 
FROM 
    ... 
GROUP BY 
    [d].[Id] 
    ,agg.ItemCount 
    ,[d].[ItemName] 

有趣的是,您已經做了這樣的聚合查詢加入,但從未使用派生表updateItem或字段MostRecent

相關問題