If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > ANSI SQL > Help needed in forming a query

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 07-02-09, 01:29
niths_86 niths_86 is offline
Registered User
 
Join Date: Jul 2009
Posts: 9
Help needed in forming a query

Hi could anyone kindly help me in forming a query to display as follows:
Suppose i have a table with 3 columns and values in it as follows :
subject exam_month marks
History jan 20
History feb 40
Maths jan 40
English feb 60
History jan 20

Now i want to display the total of marks obtained in jan for every sub. the problem i am facing is i need to display the subject name with a value 0 even if the subject is not present in Jan. So my output need to be like
subject marks
History 40
Maths 40
English 0
Please help me in forming a query to get the desired output.
The query i had used is

select distinct(subject) , isnull( sum(marks), 0) from sample_table where exam_moth = 'jan' group by subject;

But the output i got is :
History 40
Maths 20

Note: English does not get displayed

Last edited by niths_86; 07-02-09 at 01:53.
Reply With Quote
  #2 (permalink)  
Old 07-02-09, 03:00
nazirchr nazirchr is offline
Registered User
 
Join Date: Jul 2009
Posts: 1
Hi,

Please use a self outer join for the same
Reply With Quote
  #3 (permalink)  
Old 07-02-09, 06:25
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,511
Code:
SELECT s.subject
     , SUM(d.marks) AS total_marks
  FROM (
       SELECT DISTINCT subject 
         FROM sample_table
       ) AS s
LEFT OUTER
  JOIN sample_table
    ON sample_table.subject = s.subject
   AND sample_table.exam_moth = 'jan' 
GROUP 
    BY s.subject
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #4 (permalink)  
Old 07-02-09, 06:47
niths_86 niths_86 is offline
Registered User
 
Join Date: Jul 2009
Posts: 9
wow...thanks a lot, it is working perfectly fine!!
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On