【问题标题】:I am not able to get the values from the database in the order I want我无法按照我想要的顺序从数据库中获取值
【发布时间】:2015-04-10 13:03:37
【问题描述】:

我正在尝试从数据库中获取 android 条形图的值。

id   amount  status   month
1    3567       +      4
2    5673       -      3
3    2356       +      2
4     789       -      8
5    1789       +      8

请考虑这张表。 (很抱歉我无法添加图片)。因为,我需要获取条形图的值,所以我想在 x 轴上有月份,在 y 轴上有金额。条形图应该是收入与支出图表。

我已应用以下查询:

Cursor c=db1.rawQuery("select distinct month, (select sum(amount) from expenses where status like '+' group by month) as income, (select sum(amount) from expenses where status like '-' group by month)as expense from expenses", null);

我得到以下结果:

month   income   expense
4       2356       5673
3       2356       5673
2       2356       5673
8       2356       5673

而不是

month    income    expense
4        3567       null
3        null       5673
2        2356       null
8        1789       789

我希望如果有更多行(例如,month=4 和 status="+",amount=20),那么结果应该是 3587 而不是 3567。

感谢您的时间和帮助。

【问题讨论】:

    标签: android database sqlite union bar-chart


    【解决方案1】:
    select distinct month, 
        (select sum(amount) from expenses where month = t.month and status like '+' group by month) as income, 
        (select sum(amount) from expenses where month = t.month and status like '-' group by month) as expense 
    from expenses t
    

    【讨论】:

    • 它工作得非常好。万分感谢!能否请您告诉我如何让月份按排序顺序显示在图表中?
    • ... from expenses t order by month
    • 我忘了包括,数据库中的月份是 int。我用于条形图的月份是字符串数组,即我仅从月份转换的 month2[]。我现在如何排序?
    • 对不起,我听不懂。你能展示你的创建表查询吗?
    • 基本上,我在问如何按月对字符串数组进行排序,例如..Jan, Feb, Mar, Apr.....
    【解决方案2】:

    在您进行子查询的地方,您需要连接数据,因为子查询将在所有表中进行搜索。 srry 我没看到那只有一张桌子也试试这个。

    select 
       distinct month,
       (select sum(ammount) from foo as f2 where f1.month=f2.month and status='+' ) as income,
       (select sum(ammount) from foo as f3 where f1.month=f3.month and status='-') as expense
    from foo f1
    

    【讨论】:

    • 只有一张桌子。
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2011-08-07
    • 2014-08-12
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多