我有一個表像這樣最大複製
DateTime start_time not null,
DateTime end_time not null,
Status_Id int not null,
Entry_Id int not null
我希望得到一個時間段,其中只有最後開始的有效期爲一個給定的entry_id內各狀態下的計數。
我現在使用的就是這個(動態日期):
with c (Status_Id, Entry_Id, Start_Date) AS (
select Status_Id, Entry_Id, Start_Date from tbl where
(End_Date BETWEEN '19000101' AND '21000101')
AND ((Start_Date BETWEEN '19000101' AND '21000101')
OR End_Date <= '21000101'))
select Status_Id, count(*) as cnt from
(select Entry_Id, max(start_date) as start_date from c
group by Entry_Id) d inner join
c on c.Entry_Id = d.Entry_Id
and c.start_date = d.start_date
GROUP BY Status_Id WITH ROLLUP
的問題是,它的時候有一些entry_id具有多個條目的相同的起始日期計算錯誤。 (我並不特別在意選擇在這種情況下,其地位,就只有1選擇)
一些測試數據:
status_id Entry_id Start_date
496 45173 2010-09-29 18:04:33.000
490 45173 2010-09-29 18:48:20.100
495 45173 2010-09-29 19:25:29.300
489 45174 2010-09-29 18:43:01.500
493 45175 2010-09-29 18:48:00.500
493 45175 2010-09-29 21:16:02.700
489 45175 2010-09-30 17:52:12.100
493 45176 2010-09-29 17:55:21.300
492 45176 2010-09-29 18:20:52.200 <------ This is the one that gives the problems
493 45176 2010-09-29 18:20:52.200 <------ This is the one that gives the problems
結果應該是
495 1
489 2
492 1 (or 493 1)
哦,這是一個非常非常好的解決方案! (儘管您的編輯被破壞了,但是行號必須在選擇中)。它的速度也是我提出的速度的兩倍,因爲它不需要重複消除,只是一種特殊的排序 – Cine 2010-10-29 12:24:02