SQL COUNT无法与将SELECT查询嵌套在LEFT外部联接中一起使用

时间:2019-04-04 23:58:00

标签: sql sql-server tsql join

我需要计算才能在主要选择原始问题Looking to add in a Count query with Group by INTO an existing working query

中使用
--- this join works ---
LEFT OUTER JOIN
WorkItemAssignedToUserFactvw AS IATUFact 
ON 
WI.WorkItemDimKey = IATUFact.WorkItemDimKey 
AND IATUFact.DeletedDate IS NULL 
--- this part below is in both queries ---
LEFT OUTER JOIN
UserDimvw AS AssignedToUser 
ON 
IATUFact.WorkItemAssignedToUser_UserDimKey = AssignedToUser.UserDimKey 

如果我将查询更改为具有选择语句的Left外部联接,那么我将遇到错误

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

--- same query join as before except now it had an error 
LEFT OUTER JOIN
UserDimvw AS AssignedToUser 
ON 
IATUFact.WorkItemAssignedToUser_UserDimKey = AssignedToUser.UserDimKey 

错误:

  

消息207,级别16,状态1,行292无效的列名称   “ WorkItemAssignedToUser_UserDimKey”。

1 个答案:

答案 0 :(得分:1)

在您的SELECT中使用WorkItemAssignedToUser_UserDimKey,应“。”解决此问题并将其添加到..

LEFT OUTER JOIN
(
    SELECT
        WorkItemAssignedToUser_UserDimKey,
        WorkItemDimKey,
        DateKey,
        COUNT(WorkItemAssignedToUser_UserDimKey) AS Assignments
    FROM
        WorkItemAssignedToUserFactvw
    WHERE
        DeletedDate IS NULL
    GROUP BY
        WorkItemAssignedToUser_UserDimKey,
        WorkItemDimKey,
        DateKey
)
     IATUFact
        ON  WI.WorkItemDimKey = IATUFact.WorkItemDimKey

--- same query join as before except now it had an error 
LEFT OUTER JOIN
UserDimvw AS AssignedToUser 
ON 
IATUFact.WorkItemAssignedToUser_UserDimKey = AssignedToUser.UserDimKey 

也许您已经注释掉了东西,看看是否是问题所在?