简体   繁体   English

完全符合多个条件的外部联接

[英]full outer join matching on multiple criteria

Two tables I am trying to join: 我要加入的两个表:

tableA : this table contains all of the leads we won by BID and by SOURCE and by DATE. tableA :此表包含我们通过BID,SOURCE和DATE赢得的所有潜在客户。

Bid Amount = tableA.price, Source = tableA.lead_source_id, Date = tableA.time

tableB : this table contains all of the leads we lost by BID and by SOURCE and by DATE. tableB :此表包含我们按BID,SOURCE和DATE丢失的所有潜在客户。

Bid Amount = tableB.cost, Source = tableB.lead_source_id, Date = tableB.bid_at

I would like to be able to return the number of bids we WON and LOST by BID and by SOURCE and by DATE. 我希望能够按BID,SOURCE和DATE返回我们中标和中标的数量。 Often times there are only records in one table or the other (we won all bids or lost all bids), so it appears the outer join is needed. 通常,一个表或另一个表中只有记录(我们赢得了所有竞标或失去了所有竞标),因此看来需要外部联接。

Ideal output would be grouped by lead_source_id, bid amount, and time like such: 理想的输出将按lead_source_id,出价金额和时间进行分组,如下所示:

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 the following query. 请尝试以下查询。

;WITH tmp AS (
SELECT lead_source_id,  [time] AS [Date], price, COUNT(*) AS won, 0 AS lost 
FROM  tableA
GROUP BY lead_source_id, [time], price 
UNION ALL
SELECT lead_source_id, bid_at AS [Date], cost AS price, 0 AS won, COUNT(*) AS lost 
FROM tableB
GROUP BY lead_source_id, bid_at, cost)

SELECT lead_source_id AS [Lead Source ID], [Date], price AS [Bid Amount], SUM(won) AS Won , SUM(lost) AS Lost
FROM tmp
GROUP BY lead_source_id, [Date], price
ORDER BY lead_source_id, [Date]

The common table expression (tmp) calculates number of won/lost bids and the outer select groups your data by id, date and bid amounts. 通用表格表达式(tmp)计算获胜/落败的投标数量,外部选择按ID,日期和投标金额对数据进行分组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM