iven a table named products with the following columns. Write a query to retrieve the ranks of the products in decreasing order of their quantities in stock. code example

Example 1: how to use rank function in sql

BY LOVE SINGH,
Here, name and id is the column name of the table tbltest.

SELECT
	name,
	RANK () OVER ( 
		ORDER BY id DESC
	) price_rank 
FROM
	tbltest;

Example 2: sql how to partition rank

SELECT * FROM (
	SELECT
		product_id,
		product_name,
		brand_id,
		list_price,
		RANK () OVER ( 
			PARTITION BY brand_id
			ORDER BY list_price DESC
		) price_rank 
	FROM
		production.products
) t
WHERE price_rank <= 3;

Tags:

Sql Example