我有一个像...一样的sqlite表。
id | pname | ptype | amount
------------------------------------------------------
1 | aaaaa | qw | 20
2 | bbbbb | qw | 25
3 | ccccc | qw | 55
4 | aaaaa | qw | 42
我想获得像
这样的输出 id | pname | ptype | amount
------------------------------------------------------
1 | aaaaa | qw | 42
2 | bbbbb | qw | 25
3 | ccccc | qw | 55
表示具有最大金额的非重复pname ... 我应该运行哪个查询?
答案 0 :(得分:3)
在SQLite 3.7.11或更高版本(Android API级别16或更高版本)中,您只需在SELECT列表中使用MAX,其他值将保证来自具有最大值的记录:
SELECT id,
pname,
ptype,
MAX(amount) AS amount
FROM MyTable
GROUP BY pname
如果您需要使用早期版本,则需要明确检查:
SELECT *
FROM MyTable
WHERE NOT EXISTS (SELECT 1
FROM MyTable AS smaller
WHERE smaller.pname = MyTable.pname
AND smaller.amount < MyTable.amount)
答案 1 :(得分:1)
将您的查询修改为
pname
max(amount) as max_amount
放入投影中。E.g。
Cursor c = db.query(table, new String[] {"id", "pname", "ptype", "max(amount) as max_amount"},
null, null, "pname", null, null);
答案 2 :(得分:0)
SELECT * FROM table_name ORDER BY amount DESC