How to write SQL Query to get desire output-2

Sql Interview Questions:

I have a question as below:

I have a table created as

CREATE TABLE #Table1 
(
Id INT,
CreatedDate DATE,
Qty INT
)

INSERT #Table1 VALUES
(1,'2015-05-11',10),
(1,'2015-05-13',20),
(1,'2015-05-12',30),
(2,'2015-05-11',10),
(2,'2015-05-14',20),
(2,'2015-05-12',30),
(2,'2015-05-13',40)

I want output as below:

sql Query

I have below solution to get this output:

SELECT *  FROM 
(
    SELECT DENSE_RANK()  OVER (PARTITION BY i.Id ORDER BY Qty ) AS Rank,*  
    FROM #Table1 i 
) tbl WHERE Rank<3

Now that’s your turn to prove your ability, how can we get same answer using different query.

Leave a Reply