我有一個用於記錄方法調用的表。它有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