如何从sqlite中具有不同usertype的单个列中获取金额总和

时间:2017-03-31 14:08:53

标签: sqlite ionic-framework

我使用以下查询从具有不同事务类型的列中获取金额总和以下select查询显示一种事务类型的值,但我有4种事务类型,如Farmer,worker,buyer和expense。我只收取费用数据,即使其他类型有值。

表:

{
  name: 'daybook',
  columns: [
    { name: 'id', type: 'integer', default: ''},
    { name: 'date', type: 'text', default: ''},
    { name: 'user_type', type: 'text', default: ''},
    { name: 'amount_in', type: 'numeric', default: 'default 0'},
    { name: 'amount_out', type: 'numeric', default: 'default 0'},
    { name: 'other_amount', type: 'numeric', default: 'default 0'},
    { name: 'user_id', type: 'integer', default: ''},
    { name: 'description', type: 'text', default: ''},
    { name: 'transaction_type', type: 'text', default: ''},
    { name: 'client_id', type: 'integer', default: ''},
    { name: 'category', type: 'text', default: ''},
    { name: 'count', type: 'integer', default: ''},
    { name: 'cost', type: 'integer', default: ''},
    { name: 'bill_no', type: 'text', default: ''},
    { name: 'is_deleted', type: 'text', default: ''},
    { name: 'is_synced', type: 'text', default: ''}
  ]
}

查询:

 var query = 'SELECT SUM(CASE WHEN transaction_type = "FarmerAdvance" THEN amount_out ELSE 0 END) farmeradvance,SUM(CASE WHEN transaction_type = "WorkerAdvance" THEN amount_out ELSE 0 END) workeradvance,SUM(CASE WHEN transaction_type = "Expense" THEN amount_out ELSE 0 END) expense,SUM(CASE WHEN transaction_type = "BuyerPayment" THEN amount_in ELSE 0 END) income FROM daybook WHERE user_id = ?';

  return $cordovaSQLite.execute(Database.db, query, [window.localStorage['user_id']]).then(function (result) {
    if (result.rows.length > 0) {
      $log.log('dashboard items', result.rows.item(0));
      return result.rows.item(0);
    } else {
      return 0;
    }
  });

0 个答案:

没有答案