我想加入两个表:
tableA :此表包含我们通过BID,SOURCE和DATE赢得的所有潜在客户。
Bid Amount = tableA.price, Source = tableA.lead_source_id, Date = tableA.time
tableB :此表包含我们因BID,SOURCE和DATE而丢失的所有潜在客户。
Bid Amount = tableB.cost, Source = tableB.lead_source_id, Date = tableB.bid_at
我希望能够通过BID,SOURCE和DATE返回我们WON和LOST的出价数量。通常情况下,只有一个表或另一个表中的记录(我们赢得所有出价或丢失所有出价),因此看起来需要外部联接。
理想输出将按照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
答案 0 :(得分:0)
尝试以下查询。
;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]
公用表格式(tmp)计算赢/出的出价数量,外部选择按ID,日期和出价金额对您的数据进行分组。