涉及多个表的SQL计数

时间:2017-08-21 11:58:02

标签: sql

我有两张表。UniversityUniversityType。结构看起来像这样。 对于大学

    universityId universityName universityTypeId universityTypeName
        1            xyz              1                UGC
        2            abc              1                UGC
        3            lmn              2                NCT
        4            pqr              3                AICT  

UniversityType

    universityTypeId  universityTypeName
          1                UGC
          2                NCT
          3                AICT

UniversityType表是固定的。现在我想获得大学类型的计数,即UGC = 2,AICT = 1,NCT = 1.现在我写的是这样的

    SELECT universityId,universityTypeId,universityName FROM 
    University where universityTypeId=:universityTypeId";

但我没有得到正确的结果。任何人都可以告诉我。我是SQL新手。

4 个答案:

答案 0 :(得分:1)

SELECT universityTypeId, COUNT(1) 
FROM University where universityTypeId=:universityTypeId

OR

SELECT universityTypeId, COUNT(1) 
FROM University
GROUP BY universityTypeId

OR

SELECT universityTypeId, (SELECT COUNT(1) 
    FROM University where universityTypeId = UniversityType.universityTypeId)
     FROM UniversityType

答案 1 :(得分:1)

喜欢这个

SELECT universityId,universityName,count(universityTypeId) as total  FROM 
University group by universityId,universityName

除非在聚合函数

中使用,否则必须在group by子句中添加所有列列表

答案 2 :(得分:0)

select universityTypeName, COUNT(University.universityId) FROM UniversityType JOIN University  ON UniversityType.universityTypeId = University.universityTypeId GROUP BY UniversityType.universityTypeName

尝试此查询

答案 3 :(得分:0)

您需要按UniversityType.universityTypeId加入表格并计算University。所以,试试这个:

SELECT t.universityTypeName, count(u.universityId) as total 
FROM University u, UniversityType t 
WHERE u.universityTypeId = t.universityTypeId 
GROUP BY u.universityTypeName;

它给出的输出是:

UGC|2
NCT|1
AICT|1