Different result set

  • I'm playing around with T-SQL. The task I have given myself is TO FIND ALL CUSTOMERS WHO HAVE PLACED AN ORDER WITH A QUANTITY < 5.

    I first write it as a SubQuery that returns 70 records.

    I then write it as a join and it returns 170 records.

    I'm trying to work out why the different result set. Is there soemthing wrong with my queries below?

    SELECT C.*

    FROM Customers C

    WHERE CustomerID IN (SELECT CustomerID FROM Orders O

       INNER JOIN [Order Details] OD ON O.OrderID = OD.OrderID

       WHERE OD.Quantity < 5)

    SELECT C.*

    FROM Customers C INNER JOIN Orders O ON C.CustomerID = O.CustomerID

       INNER JOIN [Order Details] OD ON O.OrderID = OD.OrderID

    WHERE OD.Quantity < 5


    Kindest Regards,

  • The first query show customer once only who meets the your condition but second will show same customer many times if the customer made more than one orders and quantity less than 5 of each orders.

  • Thanks. That means I have to add a GROUP BY CLAUSE for the JOIN query to filter on the rows.


    Kindest Regards,

  • Use distinct.

    SELECT distinct C.*

    FROM Customers C INNER JOIN Orders O ON C.CustomerID = O.CustomerID

       INNER JOIN [Order Details] OD ON O.OrderID = OD.OrderID

    WHERE OD.Quantity < 5

  • No problem. Thanks.

     

    Do you know any good books where I can improve my SUBQUERY skills?


    Kindest Regards,

  • As I doubt you'll find a book especially on subquery, I would have a look at

    • The Guru's Guide to Transact SQL by Ken Henderson
    • Advanced T-SQL by Tom Moreau, Itzak Ben Gan

     

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • Ok. Thanks Frank.


    Kindest Regards,

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply