sql - full outer join matching on multiple criteria -
two tables trying join:
tablea: table contains of leads won bid , source , date.
bid amount = tablea.price, source = tablea.lead_source_id, date = tablea.time
tableb: table contains of leads lost bid , source , date.
bid amount = tableb.cost, source = tableb.lead_source_id, date = tableb.bid_at
i able return number of bids won , lost bid , source , date. times there records in 1 table or other (we won bids or lost bids), appears outer join needed.
ideal output grouped lead_source_id, bid amount, , time such:
lead source id, date, bid amount, won, lost 1, 1/1/2015, $20, 5, 0 1, 1/1/2015, $25, 0, 9 5, 1/1/2015, $30, 1, 1 10, 1/2/2015, $50, 0, 1 10, 1/2/2015, $55, 1, 0
try following query.
;with tmp ( select lead_source_id, [time] [date], price, count(*) won, 0 lost tablea group lead_source_id, [time], price union select lead_source_id, bid_at [date], cost price, 0 won, count(*) lost tableb group lead_source_id, bid_at, cost) select lead_source_id [lead source id], [date], price [bid amount], sum(won) won , sum(lost) lost tmp group lead_source_id, [date], price order lead_source_id, [date]
the common table expression (tmp) calculates number of won/lost bids , outer select groups data id, date , bid amounts.
Comments
Post a Comment