views:

325

answers:

3

Hello,

I am working with 3 tables, trying to pull a list that match certain criteria. I need a list of companies from the companies table, that have an active opportunity (iactive is 1 in opportunities table) AND have a record in the notes table of type order or order2.

 Companies Table
+------+------------------+
| cid  |     ccyname      |
+------+------------------+
| 1c   | Bobs Fish        |
| 2c   | Sheep Counters   |
| 3c   | Old Timers       |
| 4c   | Roasted Nuts     |
+------+------------------+

   Notes Table
+------+--------+--------+
| nid  |ntype   |cid     |
+------+--------+--------+
| 1n   | order  |3c      |
| 2n   | quest  |1c      |
| 3n   | order2 |2c      |
| 4n   | cancel |2c      |
+------+--------+--------+

Opportunities Table
+------+--------+--------+
| oid  |iactive | cid    |
+------+--------+--------+
| 1o   | 1      | 1c     |
| 2o   | 0      | 3c     |
| 3o   | 1      | 3c     |
| 4o   | 1      | 2c     |
+------+--------+--------+

With this example the results should be:

     Results
+----------------+--------+
| ccyname        |  oid   |
+----------------+--------+
| Old Timers     | 3o     |
| Sheep Counters | 4o     |
+----------------+--------+

Which would give me only companies that have both an active opportunity and an order or order2 note.

I have tried building this a few different ways, but I always end up with just one result or with too many. Could I get some help?

This is on SQL Server 2005.

Thanks, John

A: 

SELECT DISTINCT cid, ccyname
FROM Companies c
INNER JOIN Notes n ON n.cid = c.cid AND n.ntype = 'order2' OR n.ntype = 'order'
INNER JOIN Opportunities o ON o.cid = c.cid AND o.iactive = 1

Zannjaminderson
+1  A: 
SELECT DISTINCT(ccyname), oid
FROM Companies AS c
INNER JOIN Notes AS n ON c.cid = n.cid
INNER JOIN Opportunities AS o ON c.cid = o.cid 
WHERE n.ntype IN ('order','order2')
AND o.iactive = 1;

Caveat: Not Tested.

Noah Goodrich
I was able to get this to work and give me several results, I believe this will work. After I check the results I will report back on any issues.
John
+1  A: 
SELECT
    C.ccyname, O.oid
FROM
    Companies C
    JOIN
    Opportunities O AND O.cid = c.cid
WHERE
    O.iactive = 1
    AND
    EXISTS (SELECT * FROM Notes N
        WHERE N.ntype IN ('order', 'order2') AND N.cid = c.cid)
gbn
+1 Although other solutions will give the same result, I think using Exists matches the request of "have a record in the notes table of type order or order2" the most. Also, fields from the notes table are not required.
Jeff O