#sql #average #union
Вопрос:
можно ли получить три результата в трех столбцах с разными заголовками?
select avg (safety_score) as AVG_SAFETY from chicago_public_schools where school_type = 'ES'
union
select avg (safety_score) as AVG_SAFETY from chicago_public_schools where school_type = 'HS'
union
select avg (safety_score) as AVG_SAFETY from chicago_public_schools where school_type = 'MS'
в этом случае результат выглядит следующим образом:
средняя заработная плата
48
49.52…
49.62…
Спасибо
Тоби
Комментарии:
1. Какую базу данных вы используете?
Ответ №1:
Не уверен, в какой базе данных вы находитесь.
case
следует поработать над большинством из них
select avg(case when school_type = 'ES' then safety_score end) as AVG_SAFETY_ES,
avg(case when school_type = 'HS' then safety_score end) as AVG_SAFETY_HS,
avg(case when school_type = 'MS' then safety_score end) as AVG_SAFETY_MS
from chicago_public_schools
Ответ №2:
Попробуйте это для сервера MSSQL;
select
(select avg (safety_score) from chicago_public_schools where school_type = 'ES' ) as ES_AVG_SAFETY,
(select avg (safety_score) from chicago_public_schools where school_type = 'HS' ) as HS_AVG_SAFETY,
(select avg (safety_score) from chicago_public_schools where school_type = 'MS') as MS_AVG_SAFETY