简体   繁体   中英

PostgreSQL case multiple columns gives error column does not exist

Is it possible to run a case statement with two different columns in postgresql?

I'd like to map integers to specific values using a CASE statement. I'm able to do this with ds.ordinal but when I add dcs.status I receive the following error: column "follow_up" does not exist .

Is it possible to use multiple case statements on different columns in one SELECT statement?

How can I get case when dcs.status = 0 then "follow_up" end as "follow_up" to not return an error?

SELECT DISTINCT ON (pd.id)
           case when ds.ordinal = 1 then s.name end as "primary_specialty",
           case when ds.ordinal = 2 then s.name end as "secondary_specialty",
           case when dcs.status = 0 then "follow_up" end as "follow_up"

    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
         INNER JOIN doctor_creation_notes as dcs on dcs.doctor_profile_id = dp.id

    WHERE dp.approved IS FALSE

I would expect the query to look like this;

SELECT DISTINCT ON (pd.id)
       (case when ds.ordinal = 1 then s.name end) as primary_specialty,
       (case when ds.ordinal = 2 then s.name end) as secondary_specialty,
       (case when dcs.status = 0 then 'follow_up' end) as follow_up
FROM . . . 
WHERE dp.approved IS FALSE
ORDER BY pd.id;

In other words, I think you just need single quotes around the string constant.

I made two other changes. If you are using DISTINCT ON , then you should have an ORDER BY with the expressions in parentheses for the DISTINCT ON as the first keys in the ORDER BY . You can add more keys to get the earliest, latest, biggest, smallest, or whatever row you specifically want.

Also, I removed the double quotes from column names. You apparently have a confusion with quotes in SQL. My advice is to use single quotes only for string and date constants. Don't use double quotes, and avoid them by giving your identifiers names using only valid characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM