我有一个用于记录方法调用的表。它有LogId,MethodId,DateTime列。来自两个组的select语句的值合并为一个
我需要编写一个select语句来计算特定时间段内特定方法ID的所有日志,并显示特定方法在不同时间段内的日志数量。
的第一位是简单的:
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]
但现在我需要第二列在表上,这应该是这样的,如果它是在一个单独的语句:
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]
并不是所有的方法都会在两个时间段内记录日志,所以如果连接在这些情况下在count/previous列中插入0而不是null,那将会很好。如果某个方法在任何时期都没有任何日志,那也没关系。
我想看到的是MethodId, Count, Previous
在一个表中。我如何做到这一点?在这里
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]
之间子句不影响输出的话,但如果你有日期时间指数这可能会影响性能:
正是我需要的。 – Edgar