這個怎麼樣,這是相當簡單的,給你你需要的結果:
SELECT ID, UserID, [DateTime], TypeID
FROM Users
WHERE Users.TypeID = 1
AND NOT EXISTS (
SELECT TOP 1 1
FROM Users AS U2
WHERE U2.ID <> Users.ID
AND U2.UserID = Users.UserID
AND U2.[DateTime] BETWEEN DATEADD(MI, -15, Users.[DateTime]) AND Users.[DateTime]
AND U2.TypeID = 1)
的NOT EXISTS
限制,只顯示記錄的有前內15分鐘沒有記錄他們,所以你會看到第一個記錄在一個塊,而不是每15分鐘一個。
編輯:既然你想看到一個每15分鐘這應該離不開使用遞歸:
SELECT Users.ID, Users.UserID, Users.[DateTime], Users.TypeID
FROM
(
SELECT MIN(ID) AS ID, UserID,
DATEADD(minute, DATEDIFF(minute,0,[DateTime])/15 * 15, 0) AS [DateTime]
FROM Users
GROUP BY UserID, DATEADD(minute, DATEDIFF(minute,0,[DateTime])/15 * 15, 0)
) AS Dates
INNER JOIN Users AS Users ON Users.ID = Dates.ID
WHERE Users.TypeID = 1
AND NOT EXISTS (
SELECT TOP 1 1
FROM
(
SELECT MIN(ID) AS ID, UserID,
DATEADD(minute, DATEDIFF(minute,0,[DateTime])/15 * 15, 0) AS [DateTime]
FROM Users
GROUP BY UserID, DATEADD(minute, DATEDIFF(minute,0,[DateTime])/15 * 15, 0)
) AS Dates2
INNER JOIN Users AS U2 ON U2.ID = Dates2.ID
WHERE U2.ID <> Users.ID
AND U2.UserID = Users.UserID
AND U2.[DateTime] BETWEEN DATEADD(MI, -15, Users.[DateTime]) AND Users.[DateTime]
AND U2.TypeID = 1
)
ORDER BY Users.DateTime
如果這不起作用,請張貼更多的樣本數據,這樣我可以看到什麼是缺少的。
Edit2與上面直接相同,但現在只是使用CTE來改善可讀性並有助於提高可維護性,同時我還改進了它,以突出顯示在哪些日期時間範圍內,您將限制爲主要查詢:
WITH Dates(ID, UserID, [DateTime])
AS
(
SELECT MIN(ID) AS ID, UserID,
DATEADD(minute, DATEDIFF(minute,0,[DateTime])/15 * 15, 0) AS [DateTime]
FROM Users
WHERE Users.TypeID = 1
--AND Users.[DateTime] BETWEEN @StartDateTime AND @EndDateTime
GROUP BY UserID, DATEADD(minute, DATEDIFF(minute,0,[DateTime])/15 * 15, 0)
)
SELECT Users.ID, Users.UserID, Users.[DateTime], Users.TypeID
FROM Dates
INNER JOIN Users ON Users.ID = Dates.ID
WHERE Users.TypeID = 1
--AND Users.[DateTime] BETWEEN @StartDateTime AND @EndDateTime
AND NOT EXISTS (
SELECT TOP 1 1
FROM Dates AS Dates2
INNER JOIN Users AS U2 ON U2.ID = Dates2.ID
WHERE U2.ID <> Users.ID
AND U2.UserID = Users.UserID
AND U2.[DateTime] BETWEEN DATEADD(MI, -15, Users.[DateTime]) AND Users.[DateTime]
AND U2.TypeID = 1
)
ORDER BY Users.DateTime
另外,作爲一個性能注意,每當處理一些可能最終會被這樣的遞歸潛在可能(從其他答案),你應該馬上進行考慮,如果你能限制主查詢在一般日期範圍內即使是全年或更長的範圍
爲什麼第二行輸出有TypeID 2? –
oopsss .. fixed :) – Shay
如果每分鐘發生一次事件持續20分鐘,您希望做什麼?你應該看到第一個還是第二個記錄,一個是第一分鐘,一個是第16分鐘? – Seph