13

I have a student's table with the following fields:

student(student_id, student_name, student_avg)

I need to write a query in MySQL which will display the result as :

Serial no. => the result should also have a new column with serial number as 1,2,3,...,n like an auto increment for each row in the result.

student_id
student_name
student_avg > 4

I don't want to alter my table in any way. All I have to do is write a query which will give me the above result. I hope I am clear.

Example data:

student_id         student_name      student_avg 
 1                    abc               2.5
 2                    xyz               4.1
 3                    def               4.2     

Sample output after querying:

serial_no    student_id    student_name     student_avg
  1             2            xyz               4.1
  2             3            def               4.2
3
  • please paste ur table and sample out put
    – user1423506
    Aug 8, 2012 at 9:53
  • student_id student_name student_avg 1 abc 2.5 2 xyz 4.1 3 def 4.2 sample output serial_no student_id student_name student_avg 1 2 xyz 4.1 2 3 def 4.2
    – Aayush
    Aug 8, 2012 at 9:56
  • AFAIK there're window functions rank() over(...) and row_number() etc. for mysql 8.0 Mar 19, 2019 at 12:09

2 Answers 2

44

Try this on

SELECT  @s:=@s+1 serial_number,student_id,student_name,student_avg
FROM    students,
        (SELECT @s:= 0) AS s
WHERE
student_avg > 4;

https://stackoverflow.com/a/11096550/1423506

1
  • 1
    Found something similar before. There is one problem for me though: when I combine this with another order by, the incremental numbering is not sorted anymore, it's applied before the ordering apparently. Any ideas?
    – fluxon
    Nov 4, 2017 at 11:22
11
SET @serial=0;
SELECT @serial := @serial+1 AS `serial_number`, `column_name` FROM `table_name`;

In your particular case:

SET @serial=0;

SELECT 
   @serial := @serial+1 AS `serial_number`, 
   `student_id`, 
   `student_name`, 
   `student_avg`
FROM 
   `students`
WHERE
   `student_avg` > 4;
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.