how do I know the minimum date in a query? - sql

I have a column with various dates as timestamps!
"01/17/2014 08:25:13"
"01/17/2014 08:15:11"
"01/17/2014 09:55:12"
"01/17/2014 08:45:01"
...
...
how do I do a query to find the earliest date?

Either:
select min(stamp) from tbl
Or:
select stamp from tbl order by stamp asc limit 1
The first can also be used as a window function, if you need it on an entire set without grouping.
If you need the date in the stamp, cast it:
select min(stamp::date) from tbl
Or:
select stamp::date from tbl order by stamp asc limit 1

Related

SQL Query to extract latest 2 dates from a column

A column consists of dates only. I need to extract the latest 2 dates from the table. What is the best way to do it?
Example: Values in a table having date column as 01-01-2021, 01-02-2021, 01-03-2021
I would need 01-02-2021,01-03-2021 as my output.
You can use rank() (or row_number() if there are no dupicliates):
select t.*
from t
qualify rank() over (order by datecol desc) <= 2;
Note: If you want distinct values, you could also use:
select distinct datecol
from t
order by datecol desc
limit 2;
You can order the column and then select the top X elements that you require
Select Top 2 col_Date
from MyTable
Order by col_Date DESC
The returned result would be a column
If you need to have a single string, there is a function that can help : STRING_SPLIT

How to select the first observation in a category in PostgreSQL

My table contains different house IDs(dataid), time of observation(readtime), meter reading Basic Output
And the query is as follows Query statement :
select *
from university.gas_ert
where readtime between '01/01/2014' and '01/02/2014'
I am trying to get only the first observation of each day of all the dataids between the time span. I have tried GROUP BY, but it doesn't seem working.
Distinct ON could make your query much more simple.. More read in Documentation
Definition :
Keeps only the first row of each set of rows where the given
expressions evaluate to equal. Note that the “first row” of each set
is unpredictable unless ORDER BY is used to ensure that the desired
row appears first.
SELECT
DISTINCT ON (meter_value) meter_value,
dataid,
readtime
FROM
university.gas.ert
WHERE
readtime between '2014-01-01' and '2014-01-02'
ORDER BY
meter_value,
readtime ASC;
If you want one row for each unique dataid within the time range, you should use the DISTINCT ON construction. The following query will give you a row for each dataid for each day in the range described in the WHERE clause and lets you extend the range if you want to return rows for each day x dataid combination.
select distinct on(dataid, date_trunc('day', readtime)) *
from university.gas_ert
where readtime between '2014-01-01' and '2014-01-02'
order by dataid, date_trunc('day', readtime) asc
You can take a look at window functions to help out in this. ROW_NUMBER.
GROUP the records on the basis of day using date_trunc(ie without the time component) and then rank them on the basis of readtime asc
select *
from (
select *
,row_number() over(partition by date_trunc('day',a.readtime) order by a.readtime asc ) as rnk
from university.gas_ert a
)x
where x.rnk=1

SQL: select next available date for multiple records

I have an oracle DB.
My table has ID and DATE columns (and more).
I would like to select for every ID the next available record after a certain date. For only one ID the query would be:
SELECT * FROM my_table
WHERE id = 1 AND date >= '01.01.2018'
(just ignoring the to_date() function)
How would that look like for multiple IDs? And I do want to SELECT *.
Thanks!
We can use ROW_NUMBER here:
SELECT ID, date -- and maybe other columns
FROM
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY date) rn
FROM my_table
WHERE date >= date '2018-01-01'
) t
WHERE rn = 1
The idea here is to assign a row number to each ID partition, starting with the earliest date which occurs after the cutoff you specify. The first record from each partition would then be the immediate next date, assuming it exists.

How to select row with group into 2 specific values by Descending order?

I would like to select queries a table with group by only 2 value in specific field. Like example bellow.
I have a table that normally having 2 value each minute. But some time having more than 2 value in each minute and I have selected by descending order.
Avoid that, I want to field of minute value [TimeStamp] can be group by 2 item based descending order and skip when have more than 2 value.
SELECT TOP 10
dbo.ConRadVacuum.[TimeStamp],
dbo.ConRadVacuum.Tag,
dbo.ConRadVacuum.[Value]
FROM
ConRadVacuum
ORDER BY
[TimeStamp] DESC
I want "selected row" (32 minute) can be selected only two like the other rows
I think you can use row_number() function by partitioning over minute part of your timestamp field, something like this:
select *
from (
select *,
row_number() over (
partition by datepart(minute, cast([TimeStamp] as datetime))
--^^ I use `datepart()` over cast of your timestamp field
--If your field is `datetime` you don't need to `cast`
order by [TimeStamp] desc) seq
from t) tt
where seq <= 2;
SQL Fiddle Demo
I didn't get your question very well, but i think you can put your query in CTE and add ROW_Number to it, then select your cte where your row number field is 1 or 2

SQL How to remove duplicates within select query?

I have a table which looks like that:
As You see, there are some date duplicates, so how to select only one row for each date in that table?
the column 'id_from_other_table' is from INNER JOIN with the table above
There are multiple rows with the same date, but the time is different. Therefore, DISTINCT start_date will not work. What you need is: cast the start_date to a DATE (so the TIME part is gone), and then do a DISTINCT:
SELECT DISTINCT CAST(start_date AS DATE) FROM table;
Depending on what database you use, the type name for DATE is different.
Do you need any other information except the date? If not:
SELECT DISTINCT start_date FROM table;
You mention that there are date duplicates, but it appears they're quite unique down to the precision of seconds.
Can you clarify what precision of date you start considering dates duplicate - day, hour, minute?
In any case, you'll probably want to floor your datetime field. You didn't indicate which field is preferred when removing duplicates, so this query will prefer the last name in alphabetical order.
SELECT MAX(owner_name),
--floored to the second
dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01') AS StartDate
From MyTable
GROUP BY dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01')
Select Distinct CAST(FLOOR( CAST(start_date AS FLOAT ) )AS DATETIME) from Table
If you want to select any random single row for particular day, then
SELECT * FROM table_name GROUP BY DAY(start_date)
If you want to select single entry for each user per day, then
SELECT * FROM table_name GROUP BY DAY(start_date),owner_name
here is the solution for your query returning only one row for each date in that table
here in the solution 'tony' will occur twice as two different start dates are there for it
SELECT * FROM
(
SELECT T1.*, ROW_NUMBER() OVER(PARTITION BY TRUNC(START_DATE),OWNER_NAME ORDER BY 1,2 DESC ) RNM
FROM TABLE T1
)
WHERE RNM=1
You have to convert the "DateTime" to a "Date". Then you can easier select just one for the given date no matter the time for that date.