Search code examples
javaandroidsqlsqliteandroid-sqlite

Android SQLite Query get distinct Year values from Timestring Column


i have a SQLite Database with a Column "KEY_DATUM", which is a String in the Format "YYYY-mm-dd".

Now i want to know in which years i have entries, so getting the distinct years out of my Database. I have tried the query below but i still get duplicate Values.

Anyone spots my error?

Thanks in advance!

    public ArrayList<String> getAlleJahreSpinner() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(
            true,           //boolean distinct
            TABLE_BIER,             // String Table
            columns,                // String[] columns
            "strftime('%Y'," + KEY_DATUM + ")",  // String selection
            null,       // String[] selectionargs
            KEY_DATUM,              // String groupBy
            null,           // String having
            KEY_DATUM,              // String orderBy
            null);              // String limit
    ArrayList<String> alleJahre = new ArrayList<>();
    // add an "all"-element to the list as first entry
    alleJahre.add("gesamt");

    //iterate through cursor and get distinct year values
    cursor.moveToFirst();
    while (cursor.moveToNext()){
        String zs = cursor.getString(2);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyy-MM-dd" );
        LocalDate localDate = LocalDate.parse( zs , formatter );
        alleJahre.add(""+localDate.getYear());
        Log.d("zeit",zs);
    }
    return alleJahre;
    }

Solution

  • This is a very simple sql statement that you can execute with the method rawQuery():

    public ArrayList<String> getAlleJahreSpinner() {
        SQLiteDatabase db = this.getReadableDatabase();
        String sql = "SELECT DISTINCT strftime('%Y'," + KEY_DATUM + ") FROM " + TABLE_BIER;
        Cursor cursor = db.rawQuery(sql, null);
        ArrayList<String> alleJahre = new ArrayList<>();
        alleJahre.add("gesamt");
        while (cursor.moveToNext()) {
            String zs = cursor.getString(0);
            alleJahre.add(zs);
        }
        cursor.close();
        db.close();
        return alleJahre;
    }