开发者

Values from two group by select statements into one

开发者 https://www.devze.com 2023-04-06 05:56 出处:网络
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

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开发者_JS百科 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:

select 
    l.[MethodId], 
    sum(case when datetime between @from and @to then 1 else 0 end) as count,
    sum(case when datetime between @before and @from then 1 else 0 end) as previous
from 
    [Log] l
where 
    l.[DateTime] between @before and @to 
    and l.[MethodId] in @methodIds 
group by 
    l.[MethodId] 

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.


Try this:

select
    l.[MethodId],
    count(isnull(l.[LogId],0)) as [Previous]
from
    [Log] l (nolock)
where
    l.[DateTime] between @before and @from 
    and l.[MethodId] in @methodIds
group by
    l.[MethodId]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号