I want to select state or the workstate column. Preference is to first use the state value. If its null or empty then i want to use the workstate value.
I have the following sql:
SELECT
COUNT(id) AS participants,
COALESCE(NULLIF(state,''), workState, (select state from dbo.training where id =(SELECT top(1) trainingId
FROM dbo.Xref_Participant_Training
WHERE (participantId = dbo.Participant.id) )) ) as state
FROM dbo.Participant
WHERE EXISTS
(SELECT 1
FROM dbo.Xref_Participant_Training
WHERE (participantId = dbo.Participant.id) AND (dbo.Participant.country = 'United States'))
GROUP by COALESCE(NULLIF(state,''), workState, (select state from dbo.training where id =(SELECT top(1) trainingId
FROM dbo.Xref_Participant_Training
WHERE (participantId = dbo.Participant.id) )) )
I get the following error:
Msg 144, Level 15, State 1, Line 15
Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.
COALESCEexpression in theGROUP BY.