Get highest value from column in where clause - sql

I have table:
id date day
2 21-07 1
2 10-07 3
2 11-07 2
I need to get date which has highest day, in current example it should be 10-07.
Next query works fine, but is there way to make it more optimised?
SELECT date
FROM (SELECT date, MAX(day)
FROM some_table
WHERE id = 2
GROUP BY date
LIMIT 1) x

I would not suggest a where clause. Just use:
select date
from some_table
where id = 2
order by day desc
limit 1;

Related

how to show for every user the last two payement date and sum of mounts?

i have 2 tables where from i'm trying to extract from table 1 the last 2 taxe dates per user who were taxed for the last time on the 19/06/2022 and with product id 12 in table 2, and the sum amount of taxes, as well as the time range between the two last taxe dates as mentionned in the image bellow .
First step is to add a RANK() or ROW_NUMBER() to order the payments backwards, by id so you're only looking at the 2 last payments. Like this.
The next step is to aggregate those to get min and max dates, and sum of amount. Like this.
Lastly, you calculate the difference between min and max dates. Like this.
WITH LAST_TWO AS (
SELECT *,ROW_NUMBER() OVER(PARTITION BY id ORDER BY tax_date DESC) AS time_ago
FROM table1
QUALIFY time_ago <= 2
),
AGG AS (
SELECT
id,
MIN(tax_date) as tax_date_MIN,
MAX(tax_date) as tax_date_MAX,
SUM(amount) as amount_SUM
FROM LAST_TWO
GROUP BY id
)
SELECT id, amount_SUM, DATEDIFF(day, tax_date_MIN, tax_date_MAX) as DATE_RANGE
FROM AGG
INNER JOIN table2 ON AGG.id = table2.id
WHERE table2.product_id = 12;

Updating a table column with the 2nd oldest date in a row?

I would like to update the contents of the Date 1 column to reflect 2nd oldest date each row. The table has thousands of rows and ~15 columns, only a handful of which are dates. I've used the least funtion in the past to update this column with the oldest date in each row, but I can't figure out how to update it with the 2nd oldest date(1/15/2020 for row 1 and 04/15/2020 for row 2 in this instance). Any help would be greatly appreciated.
ID
Date 1
Date 2
Date 3
Date 4
001
01/14/2020
01/15/2020
01/16/2020
002
04/15/2020
03/20/2020
06/16/2020
The simplest option might be to unpivot:
select t.*, d.date
from mytable t
cross join lateral (
select date
from (values (t.date2), (t.date3), (t.date4)) d(date)
order by d.date
limit 1 offset 1
) d
If you wanted an update statement:
update mytable t
set date1 = (
select date
from (values (date2), (date3), (date4)) d(date)
order by d.date
limit 1 offset 1
)
Demo on DB Fiddle

Get the data with max date and max and one more column in SAS

TableA
ID LineNum Date
123 12 30JAN2016
123 15 30JAN2016
123 21 25JAN2016
How to get the ID where DATE is MAX and LineNum for that particular date should be max,
in the above table max date is 30JAN2016 and for that 15 is maximum,
Output should be:
123 15 30JAN2016
I would suggest ordering the data and choosing the first row. In Oracle, this is traditionally written as:
select a.*
from (select a.*
from tablea a
order by date desc, linenum desc
) a
where rownum = 1;
In Oracle 12c+, you can write this more simply as:
select a.*
from tablea a
order by date desc, linenum desc
fetch first 1 row only;
In SAS, assuming that your date variable is numeric, you could do a proc sort by id, date and linenum and then select the last record in a datastep.
proc sort data=in; by id date linenum; run;
data out;
set in;
by id;
if last.id;
run;
This will give one row per ID with the max date and max linenum
SAS proc sql:
proc sql;
select * from have group by id having date=max(date) and linenum=max(linnum);
quit;
I think what you want it the maximum date for each ID, and this can be performed with the following query:
select *
from
(select ID, max(Date) maxDate
from table
group by ID) a join (
select ID, Date, max(LineNum) maxLineNum
from table
group by ID, Date
) b
On a.ID = b.ID AND a.maxDate = b.Date
Explain:
You first select the maximum date for each ID (the first subquery).
You then select maximum line number for each ID and Date (second subquery).
By joining them, you will obtain the row with maximum date as well as maximum LineNum at the same time!

Query using Avg order by date

I am querying a table with dates and numbers. I need top 10 dates in desc order and a value for the average column.
SELECT TOP (10) columnName1, AVG(columnNumber1) AS AvgNumber
WHERE ....
AND ...
GROUP BY columnName1
**Order by date desc**
to get the top resent dates i need to order by date desc
rgs
i need to sort the date column and then average the top ten. using group by i have to place date in select and get 10 results...i dont want to group by date. this probably not the way
eg
HireDate LocationID
2001-01-01 1
2002-08-12 1
1999-09-01 2
1996-03-16 1
2007-05-17 1
2001-11-15 4
2000-01-01 1
2001-11-15 NULL
2003-09-30 2
2004-10-04 2
1989-04-01 1
1995-05-26 4
select top (5) avg(locationid) from Employee
order by HireDate desc
Msg 8127, Level 16, State 1, Line 2
Column "Employee.HireDate" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
Results required
HireDate LocationID
2007-05-17 1
2004-10-04 2
2003-09-30 2
2002-08-12 1
2001-11-15 4
Avg =2
To enforce the required logical order of operations, use a derived table: select top 10 rows based on the descending order of the date column, then use the result as a dataset to obtain the average from it:
SELECT AVG(Value)
FROM
(
SELECT TOP (10) Value
FROM YourTable
WHERE ...
ORDER BY DateColumn DESC
) AS s
;
The easiest way to achieve this is to add the date to the group by. If you don't want to return the date then you can wrap your result in another select to remove it, like this:
SELECT AVGLocation
FROM (SELECT TOP (5) avg(locationid) as AVGLocation, HireDate
FROM Employee
GROUP BY HireDate
ORDER BY HireDate desc) TableAliasName

Need a SQL query to get a single, max date when the max date is not unique

My apologies if this has been asked and wasn't able to find this. I've searched for a long time, with no luck.
My table is named RESULT -
DATE TEST_NUM RESULT_NUM
11/16/2010 09:27:11 AM 123456 123111
11/16/2010 09:27:11 AM 123456 123222
11/16/2010 09:27:11 AM 123456 123333
For a given TEST_NUM, I only want to return the max date just one time, and it doesn't matter what the other column entries are -
11/16/2010 09:27:11 AM 123456 123111
SELECT RESULT.DATE,
RESULT.RESULT_NUM,
RESULT.TEST_NUM
FROM RESULT
WHERE RESULT.TEST_NUM = 123456
AND RESULT.DATE = (SELECT MAX(R1.DATE)
FROM RESULT R1
WHERE r1.TEST_NUM = RESULT.TEST_NUM)
But as you guessed, I don't get 1 result - I get all three. I've tried everything! Please help this newbie!
To get the maximum date:
SELECT MAX(RESULT.DATE) FROM RESULT
To get an entire row for any one of the rows that hold the maximum date:
SELECT * FROM
(
SELECT *
FROM RESULT
WHERE RESULT.TEST_NUM = 123456
ORDER BY RESULT.DATE DESC
)
WHERE rownum = 1
UPDATE : -
select max(DATE) from RESULT where RESULT.TEST_NUM = 123456 group by RESULT.TEST_NUM
Here is an example -
select id,max (date_column) from your_table group by id
where id is the column you want the values for max date for, this will give you max date for each of the unique entries for id in that table out of the many date entries, since what I understood was that you have multiple dates and want the max.
Why won't this work
SELECT MAX(DATE) FROM TABLE
SELECT date_column FROM table GROUP BY date_column HAVING COUNT(*)>1 ORDER BY date_column DESC LIMIT 1
This will return the highest date_column ( ORDER BY date_column DESC ) that is not unique ( HAVING COUNT(*) > 1 )
select distinct max(date_column)
into variable
from table
where condition;
Adding the distinct will ensure that if the data is the same then it will only return one record.