如何在不同的表中查找行数

时间:2018-10-26 08:06:26

标签: sql postgresql

我想从两个不同的表中获取数据,一个表包含学生总数,另一个表包含特定学生信息,我如何获取学生人数 我想显示name , code, totalstudent and no.of ngo student

select 
       a.name as name, a.school_code as CODE, 
       a.num_of_student as totalstudent,
       b.COUNT (ngo_student_name) as total_student 
from 
      ngo_student as a 
      INNER JOIN student_details as b on a.name=b.ngo_student_name 
GROUP BY
      b.ngo_student_name

此查询显示错误,请指导我 谢谢

2 个答案:

答案 0 :(得分:1)

在下面尝试-您的count(b.ngo_student_name)而不是b.count(ngo_student_name) 选择列表中的其他列也应放在group by子句中

select 
       a.name as name, a.school_code as CODE, 
       count(a.num_of_student) as totalstudent,
       COUNT(b.ngo_student_name) as total_student 
from 
      ngo_student as a 
      INNER JOIN student_details as b on a.name=b.ngo_student_name 
GROUP BY
      a.name,a.school_code

答案 1 :(得分:0)

您可以尝试以下SQL语句

 SELECT A.NAME AS NAME, A.SCHOOL_CODE AS CODE, '' AS TOTALSTUDENT , '' AS [NO.OF NGO STUDENT] FROM NGO_STUDENT
UNION ALL
SELECT TOP 1 '' AS NAME, '' AS CODE, (SELECT COUNT(DISTINCT(NGO_STUDENT_NAME)) FROM NGO_STUDENT) AS TOTALSTUDENT , 
(SELECT COUNT(DISTINCT(NGO_STUDENT_NAME)) FROM STUDENT_DETAILS) AS [NO.OF NGO STUDENT]