sql 以逗号累加的结果列
sql result column accumulated with commas
我有三张表
提供商
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
可能是因为group by of pe.speciality_id
但是如果我从下面的 group by
子句中删除它,就会出现错误
providers_speciality.speciality_id' is invalid in the select list
because it is not contained in either an aggregate function or the
GROUP BY clause.
您可以像这样消除 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
我有三张表
提供商
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
可能是因为group by of pe.speciality_id
但是如果我从下面的 group by
子句中删除它,就会出现错误
providers_speciality.speciality_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
您可以像这样消除 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