Question

I'm trying to get an average salary per year from a table. I was looking into subqueries but I'm not sure if that will solve my problem. I have solved this by using a combination of more than one Sqlite query with and for-loop but it's time consuming and I want to have one query for this...But is this possible?

Tablename = salaries
Columns = user, year, salary, month

Month will go from 01-12. Column year will then have 12 inputs for same year.

This is what I have tried:

SELECT min(year), max(year) FROM salaries WHERE user='DICK';

This will give me the start and end year for salary, not what I want.

SELECT avg(salary) FROM salaries WHERE user='DICK';

This will give me average salary for all working year...almost what I want but I really want per year.

        // I took the input from "SELECT min(year), max(year) FROM salaries WHERE user='DICK';" to get min and max for start-year and end-year

        for (int i = startYearInt; i < (endYearInt + 1); i++) {
            String currentYear = "" + i;
            cursor5 = SQLiteDb.rawQuery("SELECT avg(salary) FROM "+ TABLE_NAME +" WHERE user='"+ USER_ID+"' AND year=" + currentYear, null);
            while (cursor5.moveToNext()) {
                String avgYearSalary = cursor5.getString(0);
                Log.d("log", "avgYearSalary: " + currentYear + ": " + avgYearSalary.toString());
            }

So how can I solve this if I don't want to run several queries to the table? It's a really big DB so every query will take about 30sec. I think the DB is about 2,5 million rows:)

How to make a better query so I can stop using the for loop?

Was it helpful?

Solution

This will return the average salary that DICK perceived, per year (not a specific year but all years):

cursor5 = SQLiteDb.rawQuery("SELECT avg(salary) FROM " + TABLE_NAME + " WHERE user = '" + USER_ID + "' GROUP BY year", null);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top