我正在使用游标从数据库中检索数据,但问题是我没有。同一日期的记录,我只想明确一个记录日期,相关的日期Tamt将被添加到金额字段:
我有数据库记录,如:
Sr ExpName Date Camt Tamt
--- --------- ----------- ----- -----
1 Pen 10-10-2012 10 10
2 abc 10-10-2012 30 45
3 xyz 11-10-2012 15 55
4 ggg 11-10-2012 20 75
5 aaa 11-10-2012 10 85
6 nnn 11-10-2012 10 95
dbhelper = new DbHelper(this);
db = dbhelper.getReadableDatabase();
Cursor c = db.query(DbHelper.TABLE_NAME, new String[]{"CAST(Date AS DATE)","SUM(Tamt) AS AMT"}, null, null,"CAST(Date AS DATE)", null, null);
adapter = new SimpleCursorAdapter(this, R.layout.myrow1, c, new String[]{DbHelper.C_Date,DbHelper.C_Tamt},new int[]{R.id.textView3,R.id.textView5} );
startManagingCursor(c);
lstExpense.setAdapter(adapter);
其中myrow1是一个布局文件,TextView3和TextVew5字段,我想显示输出DATE和AMOUNT。
我想要这样输出:
DATE AMOUNT
------------ ------
10-10-2012 40
11-10-2012 35
12-10-2012 10
13-10-2012 10
答案 0 :(得分:2)
这听起来像是GROUP BY和SUM aggregation function的问题。
直接使用SQLite,您的查询需要与
一致SELECT Date, SUM(Camt) AS Amount FROM Expenses GROUP BY Date;
(我假设您的数据库表名为Expenses
。)
将其转换为Android游标查询非常简单
Cursor c = db.query("Expenses",
new String[] { "Date", "SUM(Camt) AS Amount" },
null, null, "Date", null, null, null);
这应该会给你你正在寻找的结果。