嗨,这是我的输出格式:
--------------------------------------------------------------------------------
CLASS TOTAL NO OF STUDENTS STUDENTS PURCHASED REMAINING STUDENTS
1A 52 26 26
现在我想要以上述格式的结果(有多少学生属于'1A'班级和已购买学生的数量,而不是购买的学生。)
我使用此查询,但我只获得了不购买学生的结果。
select count(studentid)
from student_table
where studentid not exists (select studentid from 'purchase_table')
;
任何人都有助于解决这个问题。
答案 0 :(得分:0)
尝试
SELECT class,
COUNT(*) total,
COUNT(p.studentid) purchased,
COUNT(*) - COUNT(p.studentid) remaining
FROM student_table s LEFT JOIN
purchase_table p ON s.studentid = p.studentid
WHERE s.class = '1A'
GROUP BY class;
SQLFiddle (MySQL)
SQLFiddle (SQLServer)
答案 1 :(得分:0)
试试这个:
select st.class class
, st.cnt_tl total
, coalesce(sp.cnt_customer,0) customers
, st.cnt_tl - coalesce(sp.cnt_customer,0) remaining
from (
select s1.class
, count(*) cnt_tl
from student_table s1
group by s1.class
) st
left join (
select s2.class
, count(*) cnt_customer
from student_table s2
inner join purchase_table p on ( p.studentid = s2.studentid )
group by s2.class
) sp
on ( sp.class = st.class )
;
现场演示(sqlfiddle)here (oracle 11g r2)。