如何计算一个单元格中的数字与另一个表格中的列的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
投票

当@a_horse_with_no_name对你的帖子发表评论时,你试图从行中的number中减去varchar

(classes.amount_of_students - (SELECT COUNT(id_class) 

因为classes.amount_of_studentsVARCHAR类型。 因此,您需要更改amount_of_students的表格列classes并将其类型更改为int

ALTER TABLE classes
ALTER COLUMN amount_of_students TYPE INT

或者在你的查询中cast它到integer

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