Home > Net >  SQL Query All Columns Using Distinct on One Column Only
SQL Query All Columns Using Distinct on One Column Only

Time:11-01

I am trying to select all columns of a table with ONLY ONE column distinct

The table is

subCode Title grade section
045/01 Math 12 Grade 12.D
045/01 Math 12 Grade 12.C
045/01 Math 12 Grade 12.A
011/01 Science 12 Grade 12.D
011/01 Science 12 Grade 12.C

I want to select DISTINCT subCode with the corresponding Title, grade and section

I tried:

SELECT DISTINCT subCode ,Title, grade, section FROM TABLENAME;

but it did not return what I want.

I want it to return :

subCode Title grade section
045/01 Math 12 Grade 12.D
011/01 Science 12 Grade 12.D

CodePudding user response:

What you need is to group by columns subCode ,Title, grade to keep them non-aggregated, while apply aggregation for section such as

SELECT subCode ,Title, grade, MAX(section) AS section 
  FROM TABLENAME
 GROUP BY subCode ,Title, grade

You should be getting 5 rows with or without DISTINCT keyword in the current case. Since the combination of the columns differ for each row.

CodePudding user response:

Try to GROUP BY subCode:

SELECT DISTINCT subCode, Title, grade, section FROM TABLENAME GROUP BY subCode;
  • Related