如何获得多个相同的最大值

时间:2016-01-06 09:44:13

标签: android sqlite android-sqlite

我正在尝试构建一个查询,它给了我一些用户数量最多的用户。我可以通过ID, CONTACT_ID, ..., AMOUNT, ....获得最大值。但由于多个用户可能有相同的max值,我该如何实现呢?

例如,我将表格设为SELECT SUM(AMOUNT) AS total,CONTACT_ID FROM TABLE WHERE ID = 1 GROUP BY CONTACT_ID ORDER BY total DESC limit 1

目前我正在使用这种查询:

SELECT total,CONTACT_ID FROM
(SELECT SUM(AMOUNT) AS total,CONTACT_ID 
    FROM TABLE 
    WHERE ID = 1  
    GROUP BY CONTACT_ID     
    ORDER BY total DESC)
GROUP BY CONTACT_ID
HAVING total = MAX(total)

如果我尝试使用MAX()函数。它为我提供了所有行而不是最大行。

    tv_number.setOnClickListener(this);

2 个答案:

答案 0 :(得分:2)

在聚合完成后应用HAVING。因此,已经选择了每个组中的MAX(total)行,这意味着唯一的total是最大值。

您需要分两步执行此操作:首先确定最大总数,然后获取具有该值的所有行:

SELECT total, CONTACT_ID
FROM (SELECT SUM(AMOUNT) AS total, CONTACT_ID 
      FROM MyTable 
      WHERE ID = 1  
      GROUP BY CONTACT_ID)
WHERE total = (SELECT SUM(AMOUNT)
               FROM MyTable 
               WHERE ID = 1  
               GROUP BY CONTACT_ID
               ORDER BY 1 DESC
               LIMIT 1);

答案 1 :(得分:-1)

乍一看,我会使用辅助请求,例如:

SELECT SUM(AMOUNT) AS total,CONTACT_ID 
    FROM TABLE 
    WHERE ID = 1
    AND total=(SELECT MAX(SUM(AMOUNT)) FROM TABLE GROUP BY CONTACT_ID)
    GROUP BY CONTACT_ID     
    ORDER BY total DESC

Nota:WHERE ID = 1;来自您的第一个请求