我正在努力陷入SQL疯狂,希望有人可以提供帮助!
我有2张表基本上是记录和结果,我想将2张表加在一起,计算每条记录的结果数(0或更多),我很容易就可以了:
Select records.Id, (IsNull(Count(outcomes.Id),0)) as outcomes
from records
Left Join
outcomes
on records.Id = outcomes.Id
group by
records.Id
结果表中还有一个时间戳,我想要做的是包括我的结果集中的最后一个结果,如果我添加我的查询它会为每个记录组合生成一个记录到结果。
任何SQL专家都能指出我正确的方向吗?
干杯,
答案 0 :(得分:1)
尝试:
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