简体   繁体   English

SQLite查询返回空游标而不是0

[英]Sqlite query returns empty cursor instead of 0

I have a query which should return total Income - total expense for the given date 我有一个查询,应该返回总Income - total expense给定日期的Income - total expense

db.rawQuery("select (totIncome-totExpense) from  " +
   "((select coalesce(sum(amount),0) as totIncome from transaction_table where type=0 and date like '"+ ke+"'), " +
   "(select COALESCE(sum(amount),0) as totExpense from transaction_table where type=1 and date like '"+ ke+"'))",null);

But when there are no records for type=0 , for a given date, the query returns an empty cursor instead of -totExpense . 但是,当没有给定日期的type=0记录时,查询将返回一个空游标而不是-totExpense

You can do conditional aggregation with sum(case...) : 您可以使用sum(case...)进行条件聚合:

db.rawQuery(
  "select coalesce(sum(case type when 0 then amount else 0 end) - sum(case type when 1 then amount else 0 end), 0) as result from transaction_table where date like ?",
  new String[] {ke}
);

This way the sums are calculated with only one scan of the table. 这样,只用一次表扫描即可计算总和。
The function coalesce() is needed only for the case that there are no rows in the table for that date. 仅当表中没有该日期的行时才需要使用coalesce()函数。
I also took out from the query the date ke and passed it is a parameter, which is safer. 我还从查询中取出了日期ke并将其传递给它是一个更安全的参数。
Maybe instead of like you can use = if ke is just a date and does not contain wildchars like % or _ . 也许,而不是like您可以使用=如果ke只是一个日期,但不包含像wildchars %_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM