我有一个直通表,doctor_specialties
有一个列序号,我想用它来创建一个名为primary_specialty
和secondary_specialty
的列。 primary_specialty
的逻辑是WHERE ordinal == 1
。
如何添加primary_specialty
和secondary_specialty
列?一种方法是对WHERE
使用INNER JOIN
语句,但我认为效率较低?
SELECT pd.name AS "doctor_name",
s.name AS "primary_specialty" WHERE ds.ordinal == 1
FROM doctor_profiles AS dp
INNER JOIN doctor_specialties AS ds on dp.id = ds.doctor_profile_id
INNER JOIN specialties AS s on ds.specialty_id = s.id
所需的输出
name primary_specialty secondary_specialty
Josh Dermatology, Cosmetic Dermatology
Linda Primary Care null
答案 0 :(得分:1)
您可以使用条件聚合:
SELECT dp.name AS "doctor_name",
MAX(CASE WHEN ds.ordinal = 1 THEN s.name END) AS "primary_specialty",
MAX(CASE WHEN ds.ordinal != 2 THEN s.name END) AS "secondary_specialty"
FROM doctor_profiles AS dp
INNER JOIN doctor_specialties AS ds on dp.id = ds.doctor_profile_id
INNER JOIN specialties AS s on ds.specialty_id = s.id
GROUP BY pd.name
您可以更改现有内容,或使用包含MAX
表达式的其他CASE
聚合,以实现次要专业的逻辑。
答案 1 :(得分:1)
您需要使用case语句来实现此目的。示例在下面分享
SELECT pd.name AS "doctor_name",
case when ds.ordinal = 1 then s.name end as "primary_specialty",
case when ds.ordinal <> 1 then s.name end as "secondary_specialty"
FROM doctor_profiles AS dp
INNER JOIN doctor_specialties AS ds on dp.id = ds.doctor_profile_id
INNER JOIN specialties AS s on ds.specialty_id = s.id