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

时间:2019-04-17 09:15:19

标签: sql postgresql

我有不同课程的数据库。我的目的是计算任何课程中的免费名额。我在一个表中有一个属性,该属性显示课程中可以有多少人。在另一个表格中,我有关于学生的信息,可以在其中看到学生正在学习的课程。因此,大概我应该计算所有地点的人数和课程学习人数之间的差额。

我以以下方式进行查询:

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

1 个答案:

答案 0 :(得分:0)

正如@a_horse_with_no_name在您的帖子中评论的那样,您正在尝试从以下行中的number中减去varchar

(classes.amount_of_students - (SELECT COUNT(id_class) 

因为classes.amount_of_students的类型为VARCHAR
因此,您需要更改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)