我有三个桌子
提供者
provider_id provider_name email
1 abc abc@gmail.com
2 xyz xyz@gmail.com
特色
speciality_id speciality_name
1 Derma
2 Ortho
provider_speciality
Provider_id speciality_id
1 1
1 2
我需要像下面这样的输入
Providername Speciality_name email
abc Derma,Ortho abc@gmail.com
以下是我的查询
select
a.provider_name,
STUFF((SELECT ', ' + ff.speciality_name
FROM speciality ff
WHERE ff.speciality_id = pe.speciality_id
FOR XML PATH('')), 1, 1, '')
speciality_name,
a.email
from providers a
left join providers_speciality pe on a.provider_id = pe.provider_id
and ISNULL(1,pe.speciality_id) = pe.speciality_id
left join speciality f with (nolock) on pe.speciality_id = f.speciality_id
where
upper(a.provider_name) like upper(ISNULL('%abc%',a.provider_name))
group by a.provider_name,a.email,pe.speciality_id
给出以下结果
Providername Speciality_name email
abc Derma abc@gmail.com
abc Ortho abc@gmail.com
可能是由于pe.speciality_id的分组依据
但是如果我从下面的group by
子句中删除该错误,就会出现
providers_speciality.speciality_id'在选择列表中无效 因为它既不包含在聚合函数中,也不包含在 GROUP BY子句。
答案 0 :(得分:1)
您可以像这样消除GROUP BY:
SELECT providers.*, STUFF((
SELECT ',' + speciality_name
FROM provider_speciality
JOIN speciality ON provider_speciality.speciality_id = speciality.speciality_id
WHERE provider_speciality.provider_id = providers.provider_id
FOR XML PATH('')
), 1, 1, '') AS speciality_names
FROM providers