Reputation: 568
I have a sqlite table like...
id | pname | ptype | amount
------------------------------------------------------
1 | aaaaa | qw | 20
2 | bbbbb | qw | 25
3 | ccccc | qw | 55
4 | aaaaa | qw | 42
i want to get output like
id | pname | ptype | amount
------------------------------------------------------
1 | aaaaa | qw | 42
2 | bbbbb | qw | 25
3 | ccccc | qw | 55
means non repeative pname with maximum amount... Which query i should run?
Upvotes: 1
Views: 2034
Reputation: 180010
In SQLite 3.7.11 or later (Android API level 16 or later), you can simply use MAX in the SELECT list, and the other values will be guaranteed to come from the record with the maximum value:
SELECT id,
pname,
ptype,
MAX(amount) AS amount
FROM MyTable
GROUP BY pname
If you need to work with earlier versions, you need to check explicitly:
SELECT *
FROM MyTable
WHERE NOT EXISTS (SELECT 1
FROM MyTable AS smaller
WHERE smaller.pname = MyTable.pname
AND smaller.amount < MyTable.amount)
Upvotes: 3
Reputation: 14226
Modify your query to
pname
max(amount) as max_amount
into your projection.E.g.
Cursor c = db.query(table, new String[] {"id", "pname", "ptype", "max(amount) as max_amount"},
null, null, "pname", null, null);
Upvotes: 1