2013-05-07 17 views
0

得到兩個不同的語句單一輸出你好,這是我的輸出格式:如何使用SQL

-------------------------------------------------------------------------------- 
    CLASS TOTAL NO OF STUDENTS STUDENTS PURCHASED REMAINING STUDENTS 
    1A   52      26     26 
  1. 這裏student_table「包含學生證和類。
  2. 'purchase_table'包含學生ID購買禮服的人。

現在我想要以上述格式的結果(有多少學生屬於'1A'類,購買學生數和非購買學生數)。

我使用此查詢,但我只得到不購買學生的結果。

select count(studentid) 
    from student_table 
where studentid not exists (select studentid from 'purchase_table') 
    ; 

有人幫忙解決了這個問題。

+0

你正在使用什麼數據庫? – Sibster 2013-05-07 11:20:37

回答

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

+0

亞正是它的工作......謝謝...... – 2013-05-07 11:48:54

+0

@MuraliBala你當然歡迎。如果有幫助,請考慮** [接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)**答案。 – peterm 2013-05-07 17:03:23

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)