2011-09-21 116 views
0

我有一个用于记录方法调用的表。它有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] 

之间子句不影响输出的话,但如果你有日期时间指数这可能会影响性能:

回答

2

喜欢的东西。如果这个表格可能变大,你可能应该有这样的索引。

+0

正是我需要的。 – Edgar

1

试试这个:

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

,回答有关的结果为0,而不是空的问题,而不是如何加入两套。而且在这个特定的查询中不起作用,因为group by不显示不符合标准的值。 – Edgar

1

尝试使用全外连接:

DECLARE @from1 DATETIME, 
    @from2 DATETIME, 
    @to1 DATETIME, 
    @to2 DATETIME; 

SELECT @from1 = '2011-01-01T00:00:00.000', 
    @to1 = '2011-01-31T23:59:59.997', 
    @from2 = '2011-02-01T00:00:00.000', 
    @to2 = '2011-02-28T23:59:59.997'; 


SELECT ISNULL(a.MethodID, b.MethodID) MethodID 
    ,ISNULL(a.[Count]) CountA 
    ,ISNULL(b.[Count]) CountB 
FROM 
(
select 
    l.[MethodId], 
    count(l.[LogId]) as [Count] 
from 
    [Log] l (nolock) 
where 
    l.[DateTime] between @from1 and @to1 
    and l.[MethodId] in @methodIds 
group by 
    l.[MethodId] 
) a 
FULL OUTER JOIN 
(
select 
    l.[MethodId], 
    count(l.[LogId]) as [Previous] 
from 
    [Log] l (nolock) 
where 
    l.[DateTime] between @from2 and @to2 
    and l.[MethodId] in @methodIds 
group by 
    l.[MethodId] 
) b 
ON a.MethodID = b.MethodID 
+0

这也似乎工作,但另一种解决方案更优雅。 – Edgar

相关问题