我有两个问题:
SELECT city, count(id) as num_of_applicants
FROM(
select distinct(students.id), city
FROM STUDENTS INNER JOIN APPLICATIONS ON STUDENTS.ID = APPLICATIONS.STUDENT_ID
WHERE APPLICATIONS.COLLEGE_ID = '28'
) AS derivedTable
GROUP BY city;
SELECT city, count(id) as num_of_accepted_applicants
FROM
(select applications.id, city FROM
STUDENTS INNER JOIN APPLICATIONS ON STUDENTS.ID = APPLICATIONS.STUDENT_ID
WHERE status = 'Accepted' and college_id = '28') as tbl
GROUP BY city
一个给每个大学的申请人数量,一个给出每个大学的被接受申请人数,但是我想得到一个结果在查询(而不是)结果是这样的结果:
city | number_of_applicants | number_of_accepted_applicants
答案 0 :(得分:0)
你可以简化( fyi:我不明白你为什么使用派生表,你可以把COUNT和GROUP BY放在内部查询上)并将这些查询组合成:
SELECT city
, COUNT(*) AS num_of_applicants
, SUM( CASE
WHEN status = 'Accepted' THEN 1
ELSE 0
END
) AS num_of_accepted_applicants
FROM STUDENTS
JOIN APPLICATIONS
ON STUDENTS.ID = APPLICATIONS.STUDENT_ID
WHERE college_id='28'
GROUP BY city;
另一种方法是继续使用派生表的技术。将您的每个查询设为派生表并加入城市 - 但这样做也不会有效。