开发者

tsql distinct count subquery2

开发者 https://www.devze.com 2023-04-10 18:06 出处:网络
I am using SSMS 2008 and I need to use a subquery to return the count of unique records / client. How do I do this? Currently I am getting the error:

I am using SSMS 2008 and I need to use a subquery to return the count of unique records / client. How do I do this? Currently I am getting the error:

Msg 512, Level 16, State 1, Line 58
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or 

Here is my pseudocode currently:

    SELECT A.Program, A.PEOPLE_ID, K.EVENT_NAME, A.Program2, A.Program3
     (SELECT COUNT(DISTINCT K.EVENT_NAME) 
     FROM #TEMP1 A, evolv_cs.dbo.facility_view F, evolv_cs.dbo.people_x N, event_view K WITH (NOLOCK)
     WHERE F.group_profile_id = A.group_profile_id AND 
        K.event_definition_id = a.event_definition_id AND
        A.p开发者_JS百科eople_id = N.people_id
     GROUP BY K.EVENT_NAME) as DistinctEvent
     FROM #TEMP1 A
     JOIN event_view K WITH (NOLOCK) on K.event_definition_id = A.event_definition_id
     WHERE @START_DATE BETWEEN A.Enrolled_Date AND DATEADD(D, 14, A.Enrolled_Date)
     AND (@SERVICE IS NULL OR @SERVICE = K.event_name)
 GROUP BY 
A.Program, A.PEOPLE_ID, K.EVENT_NAME, A.Program2, A.Program3


This should work and run more efficiently.

SELECT A.Program, A.PEOPLE_ID, sub.EVENT_NAME, A.Program2, A.Program3, sub.DistinctEvent 
FROM (
    SELECT K.EVENT_NAME, COUNT(DISTINCT K.EVENT_NAME) as DistinctEvent 
    FROM #TEMP1 as A 
    JOIN evolv_cs.dbo.facility_view as F ON F.group_profile_id = A.group_profile_id 
    JOIN evolv_cs.dbo.people_x as N ON A.people_id = N.people_id 
    JOIN event_view as K WITH (NOLOCK) ON K.event_definition_id = a.event_definition_id 
    WHERE @START_DATE BETWEEN A.Enrolled_Date AND DATEADD(D, 14, A.Enrolled_Date) 
    AND (@SERVICE IS NULL OR @SERVICE = K.event_name) 
    GROUP BY K.EVENT_NAME
) as sub 
JOIN #TEMP1 as A ON A.EVENT_NAME = sub.EVENT_NAME 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号