我无法按照我想要的顺序从数据库中获取值

时间:2015-04-10 13:03:37

标签: android database sqlite union bar-chart

我正在尝试从数据库中获取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

我希望如果有更多行(例如,月份= 4和状态=“+”,金额= 20),那么3587应该是结果而不是3567。

感谢您的时间和帮助。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:-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