2011-09-21 79 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

相關問題