SQL:通过多个表将Count链接到特定值

时间:2017-10-21 18:33:25

标签: sql sql-server

我正在尝试将COUNT链接到SQL Server数据库中多个表的特定值。在这种情况下,表格仅通过相关性共享值。我正在返回我想要的值,但COUNT计算给定项目中的所有内容,而不仅仅是链接到其工作项的内容。

        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

RETURNS:在这种情况下,count应为1,但它返回整个项目的计数。

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

我错过了某个地方的连接吗?

1 个答案:

答案 0 :(得分:1)

目前,您的计数正在计算所有JOIN个实例,而不仅仅是不同的级别记录。考虑将 Item 单元级别连接转换为聚合查询连接,并在外部分组中包含count字段:

具体来说,改变:

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