tags:

views:

45

answers:

1

Hi All,

Im working myself into an SQL frenzy, hopefully someone out there can help!

I've got 2 tables which are basically Records and Outcomes, I want to join the 2 tables together, count the number of outcomes per record (0 or more) which I've got quite easily with:

Select records.Id, (IsNull(Count(outcomes.Id),0)) as outcomes
from records
Left Join
outcomes
on records.Id = outcomes.Id
group by
records.Id

The outcomes table also has a timestamp in it, what I want to do is include the last outcome in my result set, if I add that the my query it generates a record for every combination of records to outcomes.

Can any SQL expert point me in the right direction?

Cheers,

+1  A: 

try:

SELECT
    dt.Id, dt.outcomes,MAX(o.YourTimestampColumn) AS LastOne
    FROM (SELECT --basically your original query, just indented differently
              records.Id, (ISNULL(COUNT(outcomes.Id),0)) AS outcomes
              from records
                  LEFT JOIN outcomes ON records.Id = outcomes.Id
              GROUP BY records.Id
          ) dt
        INNER JOIN outcomes o ON dt.Id = o.Id
    GROUP BY dt.Id, dt.outcomes
KM
Brilliant, almost perfect! Just had to change the second Join to a left join as well otherwise I lost the records where there was nothing in outcomes.. Thanks!
HeHasMoments