Sunday, May 17, 2015

Write a SQL Program to Select every Nth record.

CREATE TABLE student(id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(4 ,'Ranga', 27, 'Male'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male'),
(8 ,'Vasu', 50, 'Female'),
(9 ,'Ranga', 27, 'Male'),
(10 ,null, 27, 'Male');

Program:
-----------------------------------------------
SELECT * FROM (
SELECT @row := @row +1 AS Rownum, name as Name FROM (SELECT @row :=0) r, student
) students
WHERE rownum %3 = 1;

Output:
-----------------------------------------------
Rownum Name
1 Ranga
4 Ranga
7 Vinod
10 (null)

0 comments: