简体   繁体   中英

How to get a single output for two different statements using sql

Hi this is my output format:

--------------------------------------------------------------------------------
    CLASS   TOTAL NO OF STUDENTS    STUDENTS PURCHASED    REMAINING STUDENTS
    1A         52                      26                    26
  1. Here 'student_table' contain student id and class.
  2. 'purchase_table' contain student id those who are purchase the dress.

now i want the result in above format (how many students are belongs to Class '1A' and count of purchased students and not purchased students).

i use this query but i get only not purchase students result.

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

anybody help to solve this problem.

Try

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)

try this one:

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

live demo (sqlfiddle) here (oracle 11g r2) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM