Question on joins

  • Hey everyone,

    I wondered if someone could explain something to me, I am trying to teach myself T-SQL from a book, and I have just done a couple of exercises, the first one is wrong and the second is correct (ran against the Adventureworks DB), although both have the same tables involved, I cant work out what makes the second one correct, or to put it another way, why the results are not the same. I'd really appreciate some explanation, I cant work it out. I think it might be the order of the joins?

    ----2 I got this wrong, I cant work out how though

    --select sum(OrderQty) as SumOfOrderQTY, p.ProductID, soh.OrderDate

    --from Production.Product as p

    --inner join sales.salesorderdetail as SOD

    --on p.ProductID = sod.ProductID

    --inner join sales.salesorderheader as SOH on soh.salesorderid = sod.SalesOrderID

    --group by p.productid, soh.OrderDate;

    ----2 This is the correct one solution.

    --select sum(orderqty) SumOfOrderQty, p.productid, soh.orderdate

    --from sales.salesorderheader as soh

    --inner join sales.salesorderdetail as sod

    --on soh.salesorderid = sod.salesorderdetailid

    --inner join production.product as p on sod.productid = p.productid

    --group by p.productid, soh.orderdat

    Thanks in advance for ANY help.

    Regards,

    D.

  • The only difference I can find is in the join between SalesOrderDetail and SalesOrderHeader. The problem is that I would believe that the first option is correct and the second one is incorrect.

    The order of the joins won't make any difference with inner joins in this case (it might give you a syntax error if you want to use a column from a table before it's mentioned on a JOIN clause).

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • I agree, the second is joining incorrectly on detailid instead of orderid.

    In addition, I would through an Order By on both of those queries so the results are easier to compare

    ORDER BY p.ProductID,SumofOrderQty;

    Jason...AKA CirqueDeSQLeil
    _______________________________________________
    I have given a name to my pain...MCM SQL Server, MVP
    SQL RNNR
    Posting Performance Based Questions - Gail Shaw[/url]
    Learn Extended Events

Viewing 3 posts - 1 through 2 (of 2 total)

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