SQL Challenges-1: Nth Highest Sale amount
SQL Challenges-1: Exercise-3 with Solution
From the following table, write a SQL query to find the Nth highest sale. Return sale amount.
Input:
Table: salesemast
Structure:
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
sale_id | int(11) | YES | |||
employee_id | int(11) | YES | |||
sale_date | date | YES | |||
sale_amt | int(11) | YES |
Data:
sale_id | employee_id | sale_date | sale_amt |
---|---|---|---|
1 | 1000 | 2012-03-08 | 4500 |
2 | 1001 | 2012-03-09 | 5500 |
3 | 1003 | 2012-04-10 | 3500 |
Sample Solution:
SQL Code(MySQL):
CREATE TABLE IF NOT EXISTS salemast(sale_id int, employee_id int, sale_date date, sale_amt int);
TRUNCATE TABLE salemast;
INSERT INTO salemast (sale_id, employee_id, sale_date, sale_amt) VALUES ('1', '1000', '2012-03-08', 4500);
INSERT INTO salemast (sale_id, employee_id, sale_date, sale_amt) VALUES ('2', '1001', '2012-03-09', 5500);
INSERT INTO salemast (sale_id, employee_id, sale_date, sale_amt) VALUES ('3', '1003', '2012-04-10', 3500);
SELECT * FROM salemast;
Sample Output:
getNthHighestSaleAmt(3)| -----------------------| 3500|
Solution-1:
# Solution
USE ‘temp';
DROP function IF EXISTS 'getNthHighestSaleAmt';
DELIMITER $$
USE 'temp'$$
# -------------------------------
CREATE FUNCTION 'getNthHighestSaleAmt' (N INT) RETURNS int(11)
BEGIN
SET N = N-1;
RETURN (
SELECT DISTINCT sale_amt FROM salemast
ORDER BY sale_amt DESC
LIMIT 1 OFFSET N
);
END$$
DELIMITER ;
# To Execute the function:
SELECT getNthHighestSaleAmt(3);
SQL Code Editor:
Contribute your code and comments through Disqus.
Previous: Third Highest Sale.
Next: Consecutive Numbers.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/sql-exercises/challenges-1/sql-challenges-1-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics