希望通过INTO现有的工作查询中的分组方式添加计数查询

时间:2019-04-04 22:22:35

标签: sql sql-server tsql join

目标: 我希望获得一个工作项被重新分配多少次的计数 据我了解,正确的查询如下:

SELECT      
    WorkItemDimvw.Id, 
    COUNT(WorkItemAssignedToUserFactvw.WorkItemAssignedToUser_UserDimKey) AS Assignments    
FROM  WorkItemDimvw INNER JOIN  WorkItemAssignedToUserFactvw 
ON WorkItemDimvw.WorkItemDimKey = WorkItemAssignedToUserFactvw.WorkItemDimKey 
GROUP BY WorkItemDimvw.Id

EXISTING查询在下面,我想知道/忘记是否应该:

  1. 只需添加COUNT(WorkItemAssignedToUserFactvw.WorkItemAssignedToUser_UserDimKey) AS Assignments,因为存在联接,但按WorkItemDimvw.Id分组。
  2. 它应该是下面“选择”中的子查询吗?

查询:

SELECT 
    SRD.ID,
    SRD.Title,
    SRD.Description,
    SRD.EntityDimKey,
    WI.WorkItemDimKey,
    IATUFact.DateKey
FROM 
    SLAConfigurationDimvw 
    INNER JOIN SLAInstanceInformationFactvw 
        ON SLAConfigurationDimvw.SLAConfigurationDimKey = SLAInstanceInformationFactvw.SLAConfigurationDimKey 
    RIGHT OUTER JOIN ServiceRequestDimvw AS SRD 
    INNER JOIN WorkItemDimvw AS WI 
        ON SRD.EntityDimKey = WI.EntityDimKey
    LEFT OUTER JOIN WorkItemAssignedToUserFactvw AS IATUFact 
        ON WI.WorkItemDimKey = IATUFact.WorkItemDimKey 
        AND IATUFact.DeletedDate IS NULL 

1 个答案:

答案 0 :(得分:1)

诀窍是在加入子查询之前,将数据汇总到子查询中。

SELECT 
    SRD.ID,
    SRD.Title,
    SRD.Description,
    SRD.EntityDimKey,
    WI.WorkItemDimKey,
    IATUFact.DateKey,
    IATUFact.Assignments
FROM 
    SLAConfigurationDimvw 
INNER JOIN
    SLAInstanceInformationFactvw 
        ON SLAConfigurationDimvw.SLAConfigurationDimKey = SLAInstanceInformationFactvw.SLAConfigurationDimKey 
RIGHT OUTER JOIN
    ServiceRequestDimvw AS SRD
        ON <you're missing something here>
INNER JOIN
    WorkItemDimvw AS WI 
        ON SRD.EntityDimKey = WI.EntityDimKey
LEFT OUTER JOIN
(
    SELECT
        WorkItemDimKey,
        DateKey,
        COUNT(WorkItemAssignedToUser_UserDimKey) AS Assignments
    FROM
        WorkItemAssignedToUserFactvw
    WHERE
        DeletedDate IS NULL
    GROUP BY
        WorkItemDimKey,
        DateKey
)
    IATUFact
        ON  WI.WorkItemDimKey = IATUFact.WorkItemDimKey