SQL SELECT子句与特定顺序的WHERE语句

时间:2018-03-19 15:18:09

标签: sql postgresql

我有一个直通表,doctor_specialties有一个列序号,我想用它来创建一个名为primary_specialtysecondary_specialty的列。 primary_specialty的逻辑是WHERE ordinal == 1

如何添加primary_specialtysecondary_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

2 个答案:

答案 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