简体   繁体   中英

SQL COUNT not working with nesting a SELECT query inside a LEFT outer join

I need a Count to work to use in my main select Original question 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 

If I change the query to have a Left outer join with a select statement then I end up with an error

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 

Error:

Msg 207, Level 16, State 1, Line 292 Invalid column name 'WorkItemAssignedToUser_UserDimKey'.

Use WorkItemAssignedToUser_UserDimKey in your SELECT "should" fix this AND ADD to the group by ..

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 

Maybe you had commented things out to see if they were the problem?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM