# 如何计算一个单元格中的数字与另一个表格中的列的SUM之间的差异

##### 问题描述投票：1回答：1

``````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;
``````

``````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.
``````

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)
);
``````
sql postgresql
##### 1个回答
0

``````(classes.amount_of_students - (SELECT COUNT(id_class)
``````

``````ALTER TABLE classes
ALTER COLUMN amount_of_students TYPE INT
``````

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