2014-02-26 19 views
1

我有一个SQLite表像...Android的 - 得到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

嗨...我解决了...... SELECT * FROM(SELECT * FROM test1 ORDER BY amount ASC)GROUP BY pname –

回答

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) 
+0

really? max()在API <16中不可用?我想,我在我的一些应用程序中使用它。 :o – flx

+0

MAX可用于所有版本,但其他值不保证来自同一记录。 (大多数其他SQL数据库会引发错误; MySQL允许这样做,但会返回随机值;这实际上是SQLite扩展。) –

+0

“其他值不能保证来自同一记录”意味着类似于'ptype'的东西可能来自不同的行? – flx

1

通过pname

  • max(amount) as max_amount到您的投影修改您的查询

    • 组。

    例如

    Cursor c = db.query(table, new String[] {"id", "pname", "ptype", "max(amount) as max_amount"}, 
         null, null, "pname", null, null); 
    
  • 0

    SELECT * FROM table_name ORDER BY amount DESC