0

I want to sort data in my Android Sqlite alphabetically and then choose only the first row for each alphabet. e.g. If the result set consists of Abc, Abd, Abe, Bbc, Bbd I want only Abc, Bbc. Is it possible using SQL?

everydayapps
  • 455
  • 1
  • 5
  • 20

1 Answers1

1

This should work for SQLite.

SELECT min(column_name)
FROM table_name
GROUP BY substr(column_name, 1, 1)

The substring syntax may differ on other systems. It groups your data by the first character, then returns the alphabetical minimum of each in the group.

-- edit (1/2)

If you need the entire row, it's probably best to use the results of the above query to find the entire row. Like so:

SELECT table_name.*
FROM table_name 
 JOIN 
    (SELECT min(column_name) AS column_name
     FROM table_name
     GROUP BY substr(column_name, 1, 1)) sub_query
 ON table_name.column_name = sub_query.column_name
 GROUP BY column_name
 HAVING table_name.ROWID = min(table_name.ROWID)

-- edit (2/2)

Added the last two lines (GROUP BY and HAVING). They are needed to avoid duplicates. If you have duplicate entries for column_name then the one with the lowest ROWID is chosen.

Jozua
  • 1,274
  • 10
  • 18