mysql - How do I return multiple results of sum based using where and Group by -
i trying perform query can sum of column based on clause , group date not behaving expect , not sure why.
i have table of transactions with:
a timestamp (transaction_date)
value (amount),
type (payin or payout),
pervious balance before transaction (carry),
, closing balance (balance).
here json export of table:
[ { "id":"2", "type":"payout", "carry":"2340", "amount":"50", "balance":"2290", "transaction_date":"2014-09-15 00:00:00", }, { "id":"1", "type":"payin", "carry":"340", "amount":"2000", "balance":"2340", "transaction_date":"2014-09-22 09:10:03", }, { "id":"3", "type":"payout", "carry":"0", "amount":"50", "balance":"0", "transaction_date":"2014-09-22 09:10:03", }, { "id":"4", "type":"payin", "carry":"1", "amount":"30", "balance":"1", "transaction_date":"2014-09-22 09:10:03", } ]
what trying achieve single row each date(calendar date, not timestamp) contains:
date ( again calendar not timestamp),
initial carry before of days transactions,
sum of payins date,
sum of payouts date,
final closing balance day.
at moment getting single result , seems ignore group (summing payins , payouts regardless of rows date)
select date(`transaction_date`) day, sum(amount) pay_in transactions type='payin' group day
this full query using (minus carry , balance)
select payins.day, payins.pay_in, payouts.pay_out (select date(`transaction_date`) day, sum(amount) pay_in transactions type='payin' group date(`transaction_date`) ) payins left join (select date(`transaction_date`) day, sum(amount) pay_out transactions type='payout' group date(`transaction_date`) ) payouts on payins.day = payouts.day group day
if makes difference using mamp 3.0.4 on osx 10.9
you don't need use subqueries in case, can use sum
case
. also, you're grouping appears working fine me returning 2 results sample data (see supplied fiddle):
select date(transaction_date) date, sum(case when type='payin' amount end)) payinsum, sum(case when type='payout' amount end) payoutsum transactions group date
Comments
Post a Comment