Potsgres SQL: select timestamp prior to max timestamp - sql

I have a table in Postgres with timestamps:
timestamp
2022-01-01 00:52:53
2022-01-01 00:57:12
...
2022-02-13 11:00:31
2022-02-13 16:45:10
How can I select the timestamp closest to max timestamp? Meaning, I want the timestamp 2022-02-13 11:00:31.
I am looking for something like max(timestamp)-1 so I can do on a recurring basis. Thank you

You can do:
select *
from (
select *,
rank() over(order by timestamp desc) as rk
from t
) x
where rk = 2
See running example at DB Fiddle.

I think the following query might meet your requirements:
SELECT MAX(date_col) FROM test WHERE date_col < (SELECT MAX(date_col) from test);
See DB Fiddle

Related

get count all with groupby timestamp into hourly intervals

I have a hive table that has a timestamp in string format as below,
20190516093836, 20190304125015, 20181115101358
I want to get row count with an aggregate timestamp into hourly as below
date_time count
-----------------------------
2019:05:16: 00:00:00 23
2019:05:16: 01:00:00 64
I followed several links like this but was unable to generate the desired results yet.
This is my final query:
SELECT
DATE_PART('day', b.date_time) AS date_prt,
DATE_PART('hour', b.date_time) AS hour_prt,
COUNT(*)
FROM
(SELECT
from_unixtime(unix_timestamp(`timestamp`, "yyyyMMddHHmmss")) AS date_time
FROM table_name
WHERE from_unixtime(unix_timestamp(`timestamp`, "yyyyMMddHHmmss"))
BETWEEN '2018-12-10 07:02:30' AND '2018-12-12 08:02:30') b
GROUP BY
date_prt, hour_prt
I hope for some guidance from you, thanks in advance
You can extract date_time already in required format 'yyyy-MM-dd HH:00:00'. I prefer using regexp_replace:
SELECT
date_time,
COUNT(*) as `count`
FROM
(SELECT
regexp_replace(`timestamp`, '^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})$','$1-$2-$3 $4:00:00') AS date_time
FROM table_name
WHERE regexp_replace(`timestamp`, '^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})$','$1-$2-$3 $4:$5:$6')
BETWEEN '2018-12-10 07:02:30' AND '2018-12-12 08:02:30') b
GROUP BY
date_time
This will also work:
from_unixtime(unix_timestamp('20190516093836', "yyyyMMddHHmmss"),'yyyy-MM-dd HH:00:00') AS date_time

select query to select closest date which is less then or equal to current date in postgresql

this is my table , name is resource_calendar.
i want to select resource_id which have effective date less then or equal to current date and most closest date to current date.
what will be the right query in postgresql?
query will
select effective date 22 for resource_id=3 and effective date 21 for resource_id=7
so result should be
id resource_id calendar_id applied_on effective_date version
19 3 6 2016-12-22 11:13:26.53 2016-12-22 0
26 7 5 2016-12-22 11:16:26.53 2016-12-21 0
SELECT t.*
FROM
(
SELECT id, resource_id, calendar_id, applied_on, effective_date, version,
MIN(ABS(EXTRACT(EPOCH FROM (current_timestamp - effective_date))))
OVER (PARTITION BY resource_id) AS diff
FROM resource_calendar
WHERE EXTRACT(EPOCH FROM (current_timestamp - effective_date)) > 0
) t
WHERE ABS(EXTRACT(EPOCH FROM (current_timestamp - t.effective_date))) = t.diff
This query forms a partition by resource_id on the resource_calendar. You can think of this partition as a logically grouping records together which have the same resource_id. For each such group of records, it computes the smallest difference between the effective_date and the current timestamp, where the effective_date be earlier than the current timestamp.
The outer query then identifies those records having this minimum timestamp difference.
Postgres has some reasonably helpful documentation on using window functions if you feel you need more information.
You can use this. A simple query
SELECT DISTINCT ON(resource_id) *
FROM planner.resource_calendar
WHERE effective_date <= CURRENT_DATE
ORDER BY resource_id, effective_date desc;

Compare datetimes from SQL Server table with a datetime from user and get the date from table closest to the user's datetime

I have a table in SQL Server 2014 with time stamps.
This is my table:
I want to compare each time stamp from my table with a time stamp that I input and get from my table the time stamp for which the datediff(table_timeStamp, #myTimestamp) is the smallest. Hope it is clear what I want. This is for a function and I want to know how can I do that in the easiest way possible?
SELECT TOP 1 * ........... order by ABS(datediff(second,table_timeStamp, #myTimestamp) )
If you want the closest date previous to the date input:
;With cteTestDates As
(
Select *, DateDiff(Second,datefield1, '2016-07-01') DateDifference
From TestDates
)
Select Top 1 *
From cteTestDates
Where DateDifference >= 0
Order By DateDifference
If you want the closest date regardless if it is in the past or future:
;With cteTestDates As
(
Select *, ABS(DateDiff(Second,datefield1, '2016-07-03')) DateDifference
From TestDates
)
Select Top 1 *
From cteTestDates
Order By DateDifference
That query works much faster if table has an index on Time_Stamp column.
The winner query will ALWAYS do a table scan and NEWER use index at all.
SELECT TOP 1 Time_Stamp FROM
SELECT Max(Time_Stamp) as Time_Stamp FROM MyTable WHERE Time_Stamp < #myTimestamp
UNION
SELECT MIN(Time_Stamp) as Time_Stamp FROM MyTable WHERE Time_Stamp > #myTimestamp)
ORDER BY 1

SQL return a value at a specific date in time

I'm trying the find a value at a certain date.
My data looks like
Date Value
2013-11-02 5
2013-10-10 8
2013-09-14 6
2013-08-15 4
How can I determine what the value was on 2013-09-30?
Obviously the answer is 6 but I can't figure out the SQL code.
Thanks
You can do it with order by and limiting the number of rows. In SQL Server syntax (and Sybase and Access):
select top 1 t.*
from table t
where date <= '2013-09-30'
order by date desc;
In MySQL (and Postgres):
select t.*
from table t
where date <= '2013-09-30'
order by date desc
limit 1;
In Oracle:
select t.*
from (select t.*
from table t
where date <= '2013-09-30'
order by date desc
) t
where rownum = 1
EDIT:
And, a SQL standard way to it (should work in any database):
select t.*
from table t
where date = (select max(date)
from table t2
where date <= '2013-09-30'
);

How to do this query?

I have this mysql table:
id - auto_increment
id_stock - int
price - double
date - date
sample data is:
1 1 10.5 2010-08-10
2 1 16.5 2010-08-11
3 2 12.5 2010-08-12
now, i have to group by id_stock and search for the MAX(date) of the stock, then i have to compare the MAX(date) to a date i have to pass.
How to do it?
Thank you really much
SELECT ...
FROM Table
GROUP BY Id_Stock
HAVING Max(Date) = YourPassedDate
You should be able to get this using 'group' and 'having' together:
select id, MAX(date) as max_date from
test group by id_stock having max_date > '2010-08-11'