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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -