Sub query Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • John Wilcox
    New Member
    • Feb 2012
    • 2

    Sub query Question

    I believe this question can be solved using sub-queries, but for whatever reason I can't make it work yet.

    If I have two queries:
    1)
    SELECT Table1.Field1 F1,
    COUNT(Table2.Fi eldA) FA
    FROM Table1 T1
    INNER JOIN Table2 T2 ON Table1.PN = Table2.PN
    AND Table1.IR = Table2.IR
    WHERE (((Table1.F1 BETWEEN '01/01/2012' AND '01/31/2012')
    AND (Table1.FieldX IS NULL)
    AND (Table2.P1 = 'P1')))
    GROUP BY Table1.F1

    2)
    SELECT Table1.Field1 F1,
    COUNT(Table2.Fi eldA) FA
    FROM Table1 T1
    INNER JOIN Table2 T2 ON Table1.PN = Table2.PN
    AND Table1.IR = Table2.IR
    WHERE (((Table1.F1 BETWEEN '01/01/2012' AND '01/31/2012')
    AND (Table1.FieldX IS NULL)
    AND (Table2.P2 = 'P1')))
    GROUP BY Table1.F1

    How could I combine these into one query? I've been trying for awhile, and normally I could do this, but I think the INNER JOIN's are messing with me.

    Thank you!
    -John
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    The queries are exactly the same. I don't see the purpose of joining them in any way or putting them in a subquery. And even if they were different, you don't say how they're related and what you're trying to do with them, so we wouldn't be able to answer the question anyways.

    Comment

    • John Wilcox
      New Member
      • Feb 2012
      • 2

      #3
      I apologize, let me explain further. Essentially there are three fields I'm dealing with.

      Field1, Field2, and Field3.

      Essentially I wish to COUNT both Field2 and Field3 up within one query.

      The issue I'm having is I only want to count the Field if the value "P1" is there.

      So the date could look like the below:
      Field1|Field2|F ield3
      1/1/2012|N|P1
      1/1/2012|P1|N
      1/4/2012|P1|N
      1/6/2012|P1|N
      1/9/2012|P1|P1

      I would need a query to display the count of P1 in both fields.

      Perhaps I'm just looking at this the wrong way or making it more complicated then it needs to be, I'm not the greatest with SQL.

      Thanks,
      -John

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        You wouldn't use a subquery for that. You would use a full outer join. Something like
        Code:
        SELECT *
        FROM (
           SELECT Field1, COUNT(*) AS CountOfP1
           FROM someTable
           WHERE Field2 = 'P1'
           GROUP BY Field1
        ) AS a FULL OUTER JOIN (
           SELECT Field1, COUNT(*) AS CountOfP1
           FROM someTable
           WHERE Field3 = 'P1'
           GROUP BY Field1
        ) AS b
        ON a.Field1 = b.Field1

        Comment

        Working...