mysql - SQL - Calculation with Union All and Join -
i have 3 sql tables, 1 each vendor. tables have 3 identical columns: (id), (spend), , (date). (id) stands product id. (spend) how spent on product. , (date) of transaction.
thanks stackoverflow, able sort total spent on each product (id) including tables. here union statement works:
select id, sum(spend) total ( select id, spend, date vendor1 date between '$datestart' , '$dateend' union select id, spend, date vendor2 date between '$datestart' , '$dateend' union select id, spend, date vendor3 date between '$datestart' , '$dateend' ) spendtotal group id order total desc
now incorporate new table (revtbl) in sql formula lists revenue earned each product (id). 4th table has same column labeled (id) 3 mentioned above. has same (date) column. however, table has different column named (rev).
i write sql statement sorts sum(rev)-sum(spend). tried including union no luck, , after reading union understand why. i'm guessing need incorporate join statement, not sure begin. please me write proper sql statement.
you can create 2 sub-queries , join them id. this:
select rev.id, total_rev - rev_total result (select id, sum(rev) total_rev rev group id) rev join (select id, sum(spend) spend_total ( select id, spend, @ vendor1 union select id, spend, @ vendor2 union select id, spend, @ vendor3 ) spendtotal group id) spend on spend.id = rev.id order result;
i removed conditions sql simplicity. changed "date" column names "at" because date sql data type far recall.
Comments
Post a Comment