Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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:

FieldTypeNullKeyDefaultExtra
sale_idint(11)YES
employee_idint(11)YES
sale_datedateYES
sale_amtint(11)YES

Data:

sale_idemployee_idsale_datesale_amt
110002012-03-084500
210012012-03-095500
310032012-04-103500

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.



SQL: Tips of the Day

SQL Server SELECT into existing table.

INSERT INTO dbo.TABLETWO
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:

INSERT INTO dbo.TABLETWO
  (col1, col2)
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

Database: SQL Server

Ref: https://bit.ly/3y6tpA3