如何在一個查詢中選擇在5秒,5分鐘,5小時,5天,5周,5個月,5年內添加的最後記錄?在一個sql查詢中在不同時間段內選擇結果
是否可以在一個查詢中選擇?
樣本記錄包括
name | added_timestamp
v | last_five_minutes
k | last_hour
l | last_hour
時間戳可以是實際時間
如何在一個查詢中選擇在5秒,5分鐘,5小時,5天,5周,5個月,5年內添加的最後記錄?在一個sql查詢中在不同時間段內選擇結果
是否可以在一個查詢中選擇?
樣本記錄包括
name | added_timestamp
v | last_five_minutes
k | last_hour
l | last_hour
時間戳可以是實際時間
雖然你沒有說的話,我懷疑你想在不同的時間段總計:
SELECT
SUM(date_added > NOW() - INTERVAL 5 SECOND) as total_in_last_5_seconds,
SUM(date_added > NOW() - INTERVAL 5 MINUTE) as total_in_last_5_minutes,
SUM(date_added > NOW() - INTERVAL 5 HOUR) as total_in_last_5_hours,
SUM(date_added > NOW() - INTERVAL 5 DAY) as total_in_last_5_days,
SUM(date_added > NOW() - INTERVAL 5 WEEK) as total_in_last_5_weeks,
SUM(date_added > NOW() - INTERVAL 5 MONTH) as total_in_last_5_months,
SUM(date_added > NOW() - INTERVAL 5 YEAR) as total_in_last_5_years
from records;
編輯:由評論
提示如果你想實際記錄添加替代,這將它們分類:
SELECT
*,
case
when date_added > NOW() - INTERVAL 5 SECOND then 'last_5_seconds'
when date_added > NOW() - INTERVAL 5 MINUTE then 'last_5_minutes'
when date_added > NOW() - INTERVAL 5 HOUR then 'last_5_hours'
when date_added > NOW() - INTERVAL 5 DAY then 'last_5_days'
when date_added > NOW() - INTERVAL 5 WEEK then 'last_5_weeks'
when date_added > NOW() - INTERVAL 5 MONTH then 'last_5_months'
when date_added > NOW() - INTERVAL 5 YEAR then 'last_5_years'
else 'ancient'
end as time_category
from records;
我實際上想要記錄,但也要感謝這個查詢。 – Anush
獲得在5年內增加了最後一個記錄僞:
SELECT * FROM records WHERE date_added > NOW() - INTERVAL 5 YEAR
然後提取5中添加記錄秒,5分鐘,5小時,5天,5周,5個月的結果。
SELECT
*, /* now just don't be lazy but specify whatever columns you want to pull */
(Timestamp >= NOW() - INTERVAL 5 SECOND) AS AddedWithinSeconds,
(Timestamp >= NOW() - INTERVAL 5 MINUTE) AS AddedWithinMinutes,
(Timestamp >= NOW() - INTERVAL 5 HOUR) AS AddedWithinHours,
(Timestamp >= NOW() - INTERVAL 5 DAY) AS AddedWithinDays,
(Timestamp >= NOW() - INTERVAL 5 WEEK) AS AddedWithinWeeks,
(Timestamp >= NOW() - INTERVAL 5 MONTH) AS AddedWithinMonths
FROM atable
WHERE Timestamp >= NOW() - INTERVAL 5 YEAR
ORDER BY
AddedWithinSeconds DESC,
AddedWithinMinutes DESC,
AddedWithinHours DESC,
AddedWithinDays DESC,
AddedWithinWeeks DESC,
AddedWithinMonths DESC
謝謝你,明天再試,讓你知道 – Anush
請婆獲取一些樣本數據和預期結果。在過去5個月插入的行將包括最近5周插入的行(以及5天和5小時....) –
您的意思是選擇'5sec-rows',*從表中選擇* UNION ALL選擇' 5min-rows',* from table where .. UNION ALL ..(etc)?你會得到5年排7次,5個月排6次等等。聽起來並不是最理想的。你爲什麼一口氣需要他們?如果是這樣,爲什麼不選擇5年組中的所有人,並在客戶端確定其他人的標籤? – Eddy