我想选择state
或workstate
列。首选是首先使用state
值。如果它为null或为空,那么我想使用workstate
值。
我有以下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) )) )
我收到以下错误:
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.
答案 0 :(得分:2)
这是对原始问题的回答。
问题是您需要将整个表达式放在group by
:
SELECT COUNT(id) AS participants,
COALESCE(NULLIF(p.state,''), p.workState) as state
FROM dbo.Participant p
WHERE EXISTS (SELECT 1
FROM dbo.Xref_Participant_Training pt
WHERE pt.participantId = p.id
) AND
p.country = 'United States'
GROUP BY COALESCE(NULLIF(p.state, ''), p.workState);
您的查询存在的问题是GROUP BY state
实际上意味着GROUP BY p.state
。但是,您希望按SELECT
。
另外:
EXISTS
子查询不需要列名。答案 1 :(得分:0)
更改GROUP BY以包含整个表达式
SELECT
COUNT(id) AS participants,
COALESCE(NULLIF(state,''), workState) as state
FROM dbo.Participant
WHERE EXISTS
(SELECT participantId
FROM dbo.Xref_Participant_Training
WHERE (participantId = dbo.Participant.id) AND (dbo.Participant.country = 'United States'))
GROUP BY COALESCE(NULLIF(state,''), workState)
对于更新的查询,当查询变得复杂时,使用派生表或cte
会更容易派生表的示例语法
select col1, col2, count(*)
from
(
select col1, col2 = coalesce(col2, col3), col4, col5
from sometable
) d
group by col1, col2