gpt4 book ai didi

sql - 使用 case 语句时,PostgreSQL 列必须出现在 GROUP BY 子句中或用于聚合函数中

转载 作者:行者123 更新时间:2023-11-29 14:32:37 25 4
gpt4 key购买 nike

我正在使用 case 语句计算两列,primary_specialtysecondary_specialty。这很好用,但是,我想在 pd.id 上执行 GROUP BY 并收到以下错误:

列“pppd.created_at”必须出现在 GROUP BY 子句中或用于聚合函数

所需的输出是每个 pd 的一行,其中有一列用于 primary_specialtysecondary_specialty

SELECT pd.id,
pd.npi,
pppd.created_at AS "date_submitted",
pppd.converted_at AS "date_approved",
dp.created_at AS "date_profile_created",
t.description AS "npi_specialty",
case when ds.ordinal = 1 then s.name end as "primary_specialty",
case when ds.ordinal = 2 then s.name end as "secondary_specialty"

FROM potential_doctors AS pd
INNER JOIN patient_profile_potential_doctors as pppd on pd.id = pppd.potential_doctor_id
INNER JOIN doctor_taxonomies AS dt on pd.id = dt.potential_doctor_id
INNER JOIN taxonomies AS t on dt.taxonomy_id = t.id
INNER JOIN doctor_profiles AS dp on pd.npi = dp.npi
INNER JOIN doctor_specialties AS ds on dp.id = ds.doctor_profile_id
INNER JOIN specialties AS s on ds.specialty_id = s.id

最佳答案

使用DISTINCT ON (pd.id) 而不是GROUP BY

SELECT DISTINCT ON (pd.id) pd.id,
pd.npi,
pppd.created_at AS "date_submitted",
pppd.converted_at AS "date_approved",
dp.created_at AS "date_profile_created",
t.description AS "npi_specialty",
case when ds.ordinal = 1 then s.name end as "primary_specialty",
case when ds.ordinal = 2 then s.name end as "secondary_specialty"

FROM potential_doctors AS pd
INNER JOIN patient_profile_potential_doctors as pppd on pd.id = pppd.potential_doctor_id
INNER JOIN doctor_taxonomies AS dt on pd.id = dt.potential_doctor_id
INNER JOIN taxonomies AS t on dt.taxonomy_id = t.id
INNER JOIN doctor_profiles AS dp on pd.npi = dp.npi
INNER JOIN doctor_specialties AS ds on dp.id = ds.doctor_profile_id
INNER JOIN specialties AS s on ds.specialty_id = s.id

关于sql - 使用 case 语句时,PostgreSQL 列必须出现在 GROUP BY 子句中或用于聚合函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49368435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com