I have a table for logging method calls. It has LogId, MethodId, DateTime columns.
I need to write a select statement that counts all logs for specific method IDs over a specific time period and also show the number of logs for the specific methods over a different time period.
The first bit is simple:
select
l.[MethodId],
count(l.[LogId]) as [Count]
from
[Log] l (nolock)
where
l.[DateTime] between @from and @to
and l.[MethodId] in @methodIds
group by
l.[MethodId]
But now I need a second column in that table, Previous, which would look like this if it was in a separate statement:
select
l.[MethodId],
count(l.[LogId]) as [Previous]
from
[Log] l (nolock)
where
l.[DateTime] between @before and @from
and l.[MethodId] in @methodIds
group by
l.[MethodId]
Not all methods will will have logs for the two time periods, so would be nice if the join would insert 0 in the count/previous columns in those cases instead of them being null. It’s ok if a method doesn’t have any logs in either periods.
What I want to see is MethodId, Count, Previous in one table. How do I make this happen?
Something like:
The BETWEEN clause in the where doesn’t affect the output then, but it might affect performance if you have an index on datetime. And if this table can get big, you probably should have such an index.