简体   繁体   中英

PostgreSQL: Counting Distinct Across Multiple Columns (Alongside Other Selections)

A simple SQL statement in PostgreSQL:

select class_offerings.semester_code as SC, class_offerings.class_code as CC,
class_offerings.class_name as CN, class_offerings.teacher_name as TN, 
count(distinct class_enrollment.semester_code, 
class_enrollment.class_code) as num_enrolled, --wrong
class_enrollment.maximum_capacity as max_enrollment 
from class_offerings natural join class_enrollment;

PostgreSQL doesn't support this syntax. What should I do instead? Expected result:

SC | CC | CN | TN | num_enrolled | max_enrollment

Never use natural join . It is an abomination, because it depends on columns having the same name. It doesn't even use properly declared foreign key relationships.

Table aliases make the query easier to write and to read. Perhaps you intend:

select o.semester_code as SC, o.class_code as CC, o.class_name as CN, o.teacher_name as TN, 
       count(*) as num_enrolled, --wrong
from class_offerings o join
     class_enrollment e
     on c.? = e.?
group by o.semester_code, o.class_code, o.class_name, o.teacher_name;

Put the columns for the join in the on clause where the ? s are.

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