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 > Simple SQL Query

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 04-29-11, 18:25
ch00kz ch00kz is offline
Registered User
 
Join Date: Apr 2011
Posts: 2
Simple SQL Query

Supplier(Sno, Sname)
Part ( Pno, Pname )
Project (Jno, Jname)
Supply (Sno, Pno, Jno)

I need to write a query to:

retrieve the part numbers that are supplied to exactly to exactly two projects

what I wrote was:

SELECT Pno FROM Supply WHERE (SELECT COUNT(Pno) from Supply)=2;

I do however think this is wrong as when I run a similar query on a table I have, it returns an empty set ... I essentially just want to pull the elements that their are 2 of in a specified column.
Reply With Quote
  #2 (permalink)  
Old 04-29-11, 23:33
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,524
your subquery counts the overall number of rows in the supply table

so unless there are exactly two rows in that table, the outer query returns nada, squadoosh, no results
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 04-30-11, 01:01
ch00kz ch00kz is offline
Registered User
 
Join Date: Apr 2011
Posts: 2
I have worked out the answer:

SELECT Pno FROM Supply
GROUP by Pno
HAVING (COUNT (Pno) = 2)

thanks
Reply With Quote
  #4 (permalink)  
Old 04-30-11, 05:51
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,524
yeah, that's it

although, as a matter of coding style, the parentheses are unnecessary, and of course since Pno is part of that table's primary key, it can't be null, so you can just count rows instead of counting non-null values...

HAVING COUNT(*) = 2
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
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