【问题标题】:I have a database and with multiple records of the same date and related amount but I only want a single record and that is date related total amount我有一个数据库,有多个相同日期和相关金额的记录,但我只想要一条记录,即与日期相关的总金额
【发布时间】:2012-10-13 19:02:51
【问题描述】:

我正在使用游标从数据库中检索数据,但问题是我没有。同一日期的记录,我只希望一个记录日期明智,相关的日期标记将添加到金额字段:

我有类似的数据库记录:

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

【问题讨论】:

  • 了解 GROUP BY 和 SUM 聚合
  • 让我们看看我是否理解正确,您想根据日期计算 Tamt 的总和吗?对吗?
  • 您想要的输出似乎与示例数据不匹配。 10-10 的“Camt”之和为 40,与您的预期输出相匹配。 “Tamt”之和为 55,与预期输出不匹配,但 确实 匹配您的查询。是哪个?
  • 亲爱的,我想要输出,比如如果我有 2 条相同日期的记录,并且两条记录的金额总和将出现在一条记录中,如日期(1)金额(相同日期金额的总和) ...

标签: android sqlite android-layout android-cursor


【解决方案1】:

这对于 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);

这应该会给你你正在寻找的结果。

【讨论】:

  • 不应该与适配器一起正常工作。适配器 = new SimpleCursorAdapter(this, R.layout.myrow1, c, new String[]{"Date","Camt"},new int[] {R.id.textView3,R.id.textView5});
猜你喜欢
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多