How to get latest rows with all columns [duplicate] - sql

This question already has answers here:
Select newest record group by username in SQL Server 2008
(4 answers)
Closed 7 years ago.
When we use group by some column information is lost ,I am looking for a query such that all columns of the table is returned while getting the latest data.
Eg for following source data the expected result is all items quantity for latest date.
Data:
Item Quantity Date
Apple 7 7/17/2015
Ball 15 7/17/2015
Cat 10 7/17/2015
Dog 8 7/19/2015
Ball 1 7/19/2015
Desired Result:
Item Quantity Date
Apple 7 7/17/2015
Ball 1 7/19/2015
Cat 10 7/17/2015
Dog 8 7/19/2015
Here if we use group by we loose the Quantity as it will be neither be in group by nor in aggregation.
This table does not have a id key so subquery could not be used.

You would use row_number():
select item, quantity, date
from (select t.*,
row_number() over (partition by item order by date desc) as seqnum
from t
) t
where seqnum = 1;

Related

SQL Query to sort date based on two column

I have following data in table RATING and i want to sort this based on Rating and Year.
Database MS SQL Server
Unsorted data in Table
ID PlayerName Rating Year
1 A 8 2022
2 B 8 2022
3 C 0 2022
4 A 7 2020
5 B 6 2020
6 C 6 2020
7 E 5 2020
8 D 5 2020
9 D 5 2022
Data should show as below
ID PlayerName Rating Year
1 A 8 2022
2 B 8 2022
3 D 5 2022
9 C 0 2022
4 A 7 2020
5 B 6 2020
6 C 6 2020
7 E 5 2020
8 D 5 2020
I am not able to get it right i used following Query
SELECT ID, PlayerName, Rating, Year
FROM RATING
Where Year IN (SELECT Year from Rating)
order by year DESC
but it doesn't get the correct order as i am not able to use order by clause in sub query as it generates error The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Event two column sort is not working properly
SELECT ID, PlayerName, Rating, Year
FROM RATING
order by Rating, Year
You can try to ORDER BY year DESC first then Rating DESC
SELECT ID, PlayerName, Rating, [Year]
FROM RATING
order by [Year] DESC,Rating DESC
Year is a keyword in sqlserver, I would use brackets to contain it.
Your attempt is not bad so far. But there are two things you need to change.
First: The column with the higher priority for your sorting is the column "year", so this has to be used first, and then the column "rating".
Second: You must add the key word "DESC" to begin with the newest year and the highest ranking.
So your query should be this one:
SELECT * FROM rating ORDER BY year DESC, rating DESC;
You can see this is working here: db<>fiddle
If you can rename the columns on your DB, I recommend to do not use SQL key words as column names (in your example, this the column "year") and to do not use column names that are identic to the table names (in your case, you could rename the table "rating" to "ratings" or similar).
Both of this is of course possible, but could sometimes be bad to read and let increase the risk of issues.

Increment row number based on value 1 and value 2 [duplicate]

This question already has answers here:
How to use RANK() in SQL Server
(8 answers)
Closed 3 years ago.
How can I create a sequential value based on two rows within a table, for example, let's say I have a table containing an employee's ID and work state. I would expect the following values:
ID State Expected Value
-----------------------------
1 NY 1
1 PA 2
1 NY 1
2 NC 1
2 FL 2
2 MN 3
You can use dense_rank():
select t.*,
dense_rank() over (partition by id order by state) as expected
from t;

how get first row from duplicata values Oracle SQL query [duplicate]

This question already has answers here:
Fetch the rows which have the Max value for a column for each distinct value of another column
(35 answers)
Get top results for each group (in Oracle)
(5 answers)
Select latest row for each group from oracle
(3 answers)
How to get only one record for each duplicate rows of the id in oracle?
(3 answers)
Closed 3 years ago.
Below you can find my table with values (there are no constraints on my table):
SELECT DISTINCT * FROM khalil;
outputs:
ID VALUE
-- -------
1 yassine
1 khalil
2 amine
I need to get the first row when I have duplicate values.
I have two rows with id = 1 so, in this case, I need that the first one,
which is id = 1 and value = 'yassine'
SELECT * FROM khalil
WHERE ROWID IN (SELECT MIN(ROWID) FROM khalil GROUP BY id)
ORDER BY id
This will return the first row for each id.
If you don't really care which value you'll get (unless there's something you can use to distinguish values), aggregates - such as min or max - can help:
SQL> select id,
2 max(value) value
3 from khalil
4 group by id
5 order by id;
ID VALUE
---------- --------------------
1 yassine
2 amine
SQL>
Alternatively, using analytic functions (such as row_number, which lets you sort values), you'd do it as follows:
SQL> with temp as
2 (select id,
3 value,
4 row_number() over (partition by id order by value desc) rn
5 from khalil
6 )
7 select id,
8 value
9 from temp
10 where rn = 1
11 order by id;
ID VALUE
---------- --------------------
1 yassine
2 amine
SQL>

Find second highest record from oracle db [duplicate]

This question already has answers here:
How to get second largest or third largest entry from a table [duplicate]
(12 answers)
Closed 4 years ago.
I have the following data:
id date mia
1 1/1/2017 3
1 1/2/2017 1
1 1/3/2017 2
2 1/4/2017 1
2 1/5/2017 4
2 1/6/2017 6
.
.
.
.
and so on.
If I give input as id=1 I should fetch record of 2017-02-01 and if input id=2 then record of 2017-05-01 i.e record of previous month of the highest date.
You could use:
SELECT *
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY id ORDER BY mia DESC) AS rn
FROM table) sub
WHERE rn = 2;
you may not define a column named as date, instead i use date_.
For former versions you may refer to #lad2025 's answer, if you're on oracle12c, you may query with the following :
select min(date_) min_date
from
(
select date_
from mytable
where id = &i_id
group by id, date_
order by date_
fetch first 2 rows only
);

Derby DB last x row average

I have the following table structure.
ITEM TOTAL
----------- -----------------
ID | TITLE ID |ITEMID|VALUE
1 A 1 2 6
2 B 2 1 4
3 C 3 3 3
4 D 4 3 8
5 E 5 1 2
6 F 6 5 4
7 4 5
8 2 8
9 2 7
10 1 3
11 2 2
12 3 6
I am using Apache Derby DB. I need to perform the average calculation in SQL. I need to show the list of item IDs and their average total of the last 3 records.
That is, for ITEM.ID 1, I will go to TOTAL table and select the last 3 records of the rows which are associated with the ITEMID 1. And take average of them. In Derby database, I am able to do this for a given item ID but I cannot make it without giving a specific ID. Let me show you what I've done it.
SELECT ITEM.ID, AVG(VALUE) FROM ITEM, TOTAL WHERE TOTAL.ITEMID = ITEM.ID GROUP BY ITEM.ID
This SQL gives the average of all items in a list. But this calculates for all values of the total tables. I need last 3 records only. So I changed the SQL to this:
SELECT AVG(VALUE) FROM (SELECT ROW_NUMBER() OVER() AS ROWNUM, TOTAL.* FROM TOTAL WHERE ITEMID = 1) AS TR WHERE ROWNUM > (SELECT COUNT(ID) FROM TOTAL WHERE ITEMID = 1) - 3
This works if I supply the item ID 1 or 2 etc. But I cannot do this for all items without giving an item ID.
I tried to do the same thing in ORACLE using partition and it worked. But derby does not support partitioning. There is WINDOW but I could not make use of it.
Oracle one
SELECT ITEMID, AVG(VALUE) FROM(SELECT ITEMID, VALUE, COUNT(*) OVER (PARTITION BY ITEMID) QTY, ROW_NUMBER() OVER (PARTITION BY ITEMID ORDER BY ID) IDX FROM TOTAL ORDER BY ITEMID, ID) WHERE IDX > QTY -3 GROUP BY ITEMID ORDER BY ITEMID
I need to use derby DB for its portability.
The desired output is this
RESULT
-----------------
ITEMID | AVERAGE
1 (9/3)
2 (17/3)
3 (17/3)
4 (5/1)
5 (4/1)
6 NULL
As you have noticed, Derby's support for the SQL 2003 "OLAP Operations" support is incomplete.
There was some initial work (see https://wiki.apache.org/db-derby/OLAPOperations), but that work was only partially completed.
I don't believe anyone is currently working on adding more functionality to Derby in this area.
So yes, Derby has a row_number function, but no, Derby does not (currently) have partition by.