我想在sum
的行中获取sqlite
个类似项目。
例如, x 的所有值, y 的所有值以及 z 的所有值。我知道如何在我的查询中使用WHERE
子句,但问题是它需要我将值与另一个参数进行比较。例如,像这样的查询:
select sum(number_column) from your_table where number_column = 'some_number'
从上面来看,我没有'some_number'
来比较。所以我需要一种方法来为每个相似的行添加所有值,有点像将它们组合在一起。
所以我最终会得到类似的东西:
x 25
y 24
z 16
这可能吗?欢迎任何建议。
编辑: 在克里斯蒂安的建议之后我尝试了这个:
private void getSumOfGroupedTime() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT " + KEY_CREATED_AT_AM_PM + ",sum(quantity) as sum FROM " + TABLE_SALES
+ " GROUP BY " + KEY_CREATED_AT_AM_PM, null);
c.moveToFirst();
double i = c.getDouble(0);
Log.d("sum_values_", String.valueOf(i));
c.close();
}
But it returns 1 for the three similar items i added in which each of these items have 1 as quantity. I expected 3. I'm i doing it wrong?

答案 0 :(得分:1)
假设您有一个具有以下结构的表:
+----------------+--------+
| KEY_CREATED_AT | number |
+----------------+--------+
| a | 132 |
| e | 264 |
| f | 142 |
| x | 132 |
| y | 122 |
| z | 112 |
+----------------+--------+
为了获得这些单独值的总和,您可以使用group by
所以查询将是这样的:
SELECT KEY_CREATED_AT,sum(number) as sum FROM table_name
GROUP BY KEY_CREATED_AT
此处示例:sqlfiddle
private void getSumOfGroupedTime() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT " + KEY_CREATED_AT_AM_PM + ",sum(quantity) as sum FROM " + TABLE_SALES
+ " GROUP BY " + KEY_CREATED_AT_AM_PM, null);
try {
while (c.moveToNext()) {
Double sum = c.getDouble(1);
Log.d("Sum is: " + sum);
}
} finally {
c.close();
}
}