简体   繁体   中英

How to count the difference between number from one cell and SUM of the column from another table

I have database of the different courses. My aim is to count an amount of free places on any course. I have an attribute in one table, which shows how many people can be on course. And in another table I have information about the students, where I can see which course student is studying. So, probably I should count the difference between the umber of all places and count amount of students on course.

I did the query in the following way:

SELECT (classes.amount_of_students - (SELECT COUNT(id_class) 
                                      FROM classes_students 
                                      WHERE id_class = 1)) AS free_places 
FROM classes 
  INNER JOIN classes_students ON classes.id_class = classes_students.id_class;

But unfortunately I have the following error:

ERROR:  operator does not exist: character varying - bigint
LINE 1: SELECT (classes.amount_of_students - (SELECT COUNT(id_class)...
                                           ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

So, what's the problem and how can I solve it?

UPD

classes_student

 id_class | id_student 
----------+------------
        1 |          1
        2 |          2
        1 |          3

students

id_student |  name  |  last_name   |      email      |   login   | password 
------------+--------+--------------+-----------------+-----------+----------
          1 | Serhei | Mikhailovski | serega@mail.ru  | serzh     | 12345
          2 | Bogdan | Zaitsev      | zaitsev@mail.ru | bodyaga   | qwerty
          3 | Vadim  | Yachin       | yachin@mail.ru  | yanchilla | 13371488


CREATE TABLE classes_students (
    id_class SERIAL REFERENCES classes (id_class),
    id_student SERIAL REFERENCES student (id_student),
    PRIMARY KEY (id_class, id_student)
);

    CREATE TABLE classes (
    id_class SERIAL PRIMARY KEY,
    amount_of_hours VARCHAR NOT NULL,
    amount_of_students VARCHAR NOT NULL,
    id_subject SERIAL REFERENCES subject (id_subject),
    id_teacher SERIAL REFERENCES teacher (id_teacher)
);  

As @a_horse_with_no_name commented on your post, you are trying to subtract a number from a varchar in the line:

(classes.amount_of_students - (SELECT COUNT(id_class) 

Because classes.amount_of_students is of type VARCHAR .
Therefore you need to either alter the table column amount_of_students of classes and change its type to int :

ALTER TABLE classes
ALTER COLUMN amount_of_students TYPE INT

Or cast it to integer in your query:

(nullif(classes.amount_of_students, '')::int - (SELECT COUNT(id_class) 

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