Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trying to include a COUNT from another table... 1

Status
Not open for further replies.

Amesville

Programmer
Oct 10, 2011
93
US
Hi Folks

I'm trying to collect data from two tables where I would ordinarily use a left join on the columns that relate the tables. But I'm trying to bring back a count of items from the second table where on the column being used where the table repation would take place. Something like this:

Code:
SELECT COUNT(wb.WaybillID), 
    Tr.TrID, 
    Tr.TrName, 
    CAST(Tr.trMaxCars * (Tr.TrPctThru * 0.01) AS integer) as TrCarLimit, 
    Tr.TrFromStagingArea 
FROM Train Tr LEFT JOIN Waybill wb ON tr.TrID = wb.TrainAssignment WHERE Tr.TrOriginateOL = 'Y' GROUP BY Tr.TrID
 
Sorry, somehow that got posted before I was done. Anyway, this statement tells me that Tr.TrID is invalid in the select because it doesn't appear in the GROUP BY Clause. I'm not sure how to fix this, I'm afraid I might have to break this down into a cursor? Can anyone suggest a fix?

Thanks

Craig
 
There are several ways you can write this query to return the results you are looking for. The following is called a derived table method. Basically, you write a query that returns the minimum data you need, and then you wrap the query in parenthesis and treat it (from the aspect of the outer query) as though it was a separate table. Like this:

Code:
SELECT [!]wb.WaybillCount[/!], 
       Tr.TrID, 
       Tr.TrName, 
       CAST(Tr.trMaxCars * (Tr.TrPctThru * 0.01) AS integer) as TrCarLimit, 
       Tr.TrFromStagingArea 
FROM   Train Tr 
       LEFT JOIN [!]([/!]
         Select TrainAssignment, 
                Count(WayBillId) As WayBillCount
         From   WayBill
         Group By TrainAssignment
         [!]) As wb[/!]
         ON tr.TrID = [!]wb.TrainAssignment [/!]
WHERE Tr.TrOriginateOL = 'Y'


-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Thank you George! That did the trick. I will take a good look at it and try to learn something from it... :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top