How to retrieve records for last 30 minutes in MS SQL?
Change this (CURRENT_TIMESTAMP-30)
To This: DateADD(mi, -30, Current_TimeStamp)
To get the current date use GetDate().
MSDN Link to DateAdd Function
MSDN Link to Get Date Function
Get data from last 30 minutes and get the latest rows
If you are wanting the latest row from the last 30 minutes for each unique "mmsi" that has one, then using a join to a subquery where you find the max timestamps first should work, like:
SELECT timestamp, a.mmsi, navstatus, rot, sog, lon, lat, cog, thead, man, mtype
FROM ais_cnb a INNER JOIN
(SELECT mmsi, MAX(timestamp) AS max_timestamp FROM ais_cnb
WHERE timestamp > (now() - interval 30 minute)
GROUP BY mmsi) t
ON ((timestamp = t.max_timestamp) AND (a.mmsi = t.mmsi))
Query to find the records creating in last 30 mins and then the records created in last 1 hour
Your idea is correct, but the proper syntax is this:
SELECT "last 30 minutes" as t, category_id, count(*) as cnt
FROM items
WHERE created_at >= NOW() - INTERVAL 30 MINUTE
GROUP BY category_id
UNION ALL
SELECT "last 1 hour" as t, category_id, count(*) as cnt
FROM items
WHERE
created_at < NOW() - INTERVAL 30 MINUTE
AND created_at >= NOW() - INTERVAL 60 MINUTE
GROUP BY category_id
...etc...
This query will count the events in the last 30 minutes, grouped by category_id, and then all events in the last hour but not in the last 30 minutes.
UNION ALL
is better than UNION on this context because UNION will return unique rows.
Edit
Based on your updated question, I think you are looking for this:
SELECT items.*
FROM items
WHERE created_at>=NOW() - INTERVAL 60 MINUTE
ORDER BY
(created_at >= NOW() - INTERVAL 30 MINUTE) DESC,
category_id
if you have more intervals then you can use this:
SELECT items.*
FROM items
WHERE created_at>=NOW() - INTERVAL 120 MINUTE
ORDER BY
(created_at >= NOW() - INTERVAL 30 MINUTE) DESC,
(created_at >= NOW() - INTERVAL 60 MINUTE) DESC,
category_id
Related Topics
How to Combine Two Completely Different SQL Queries into One Result
How to Select All the Columns of a Table Except One Column
How to Use SQL Like Condition With Multiple Values in Postgresql
How to Include Results of SQL Count If Count=0
Remove Decimal Values Using SQL Query
Getting Two Counts and Then Dividing Them
How to Check If More Than One Column Is Not Null Per Record
How to Calculate Percentage of Counts in SQL
Auto Increment the Column Value by 1 Conditionally in Select Query in SQL
Sql Select Count for Multiple Columns in a Single Query
Splitting Date into 2 Columns (Date + Time) in SQL
A SQL Query to Get All the Records Where 5 Columns Are Same But Only One Column Is Different
Using a Select Statement for Columns With Spaces in It
How to Replace Single-Quote With Double-Quote in SQL Query - Oracle 10G
Mysql Workbench Closes Unexpectedly
Unable to Get Min and Max Time from a Datetime Column from Every Backday
Convert Varchar Mmddyyyy to Mm/Dd/Yyyy Datetime and Select the Most Recent Date Only