sql - How to show the sum total of a user using select query in sqlite -
i having 2 tables 1 store contact details of user (contact table) , other store daily transaction of user (daybook table). daybook table consist of contact_id acts fk.i have used select query inner join user individual total amount query not showing result of user can tell me wrong in query.
contact table:
name: 'contacts', columns: [ { name: 'id', type: 'integer primary key', default: ''}, { name: 'name', type: 'text', default: ''}, { name: 'mobile_no', type: 'text', default: ''}, { name: 'location', type: 'text', default: ''}, { name: 'type', type: 'text', default: ''}, { name: 'user_id', type: 'integer', default: ''}, { name: 'is_deleted', type: 'text', default: ''}, { name: 'is_synced', type: 'text', default: ''} ] },
daybook table:
{ 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: 'sub_category', type: 'text', default: ''}, { name: 'contact_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: 'farmer_id', type: 'text', default: ''}, { name: 'is_deleted', type: 'text', default: ''}, { name: 'is_synced', type: 'text', default: ''} ] },
query used:
select contacts.name, ifnull(sum(daybook.amount_in),0) amount_in, ifnull(sum(daybook.amount_out),0) amount_out, ifnull(sum(daybook.other_amount),0) other_amount daybook inner join contacts on contacts.id = daybook.contact_id daybook.user_type = ? , daybook.user_id = ?;'
result needed :
name amount_in amount_out other_amout sankar 50000 0 3000
i think need group by
:
select c.name, coalesce(sum(db.amount_in), 0) amount_in, coalesce(sum(db.amount_out), 0) amount_out, coalesce(sum(db.other_amount), 0) other_amount daybook db inner join contacts c on c.id = db.contact_id db.user_type = ? , db.user_id = ? group c.name;
note other changes:
coalesce()
ratherifnull()
. former ansi standard function.- the use of table aliases. makes queries easier write , read.
Comments
Post a Comment