问题描述
store_id industry_id cust_id amount gender age
1 100 1000 1.00 M 20
2 100 1000 2.05 M 20
3 100 1000 3.15 M 20
4 200 2000 5.00 F 30
5 200 2000 6.00 F 30
还有另一个像这样的表t2
:
store_id industry_id cust_id amount
10 100 1000 10.00
20 200 2000 11.00
假设我们要构建一个表,其中包含每个行业中给定客户的所有交易。换句话说,是这样的:
store_id. industry_id. cust_id. amount
1 100 1000 1.00
2 100 1000 2.05
3 100 1000 3.15
4 200 2000 5.00
5 200 2000 6.00
10 100 1000 10.00
20 200 2000 11.00
我正在尝试通过在下面的查询中使用联接和合并语句来执行此操作,但是它不起作用,因为每一行在amount
中的t1
列中都有一个条目,即,没有任何NULL值可供合并语句使用。使用联接执行此操作的最佳方法是什么?
SELECT
a.store_id,a.industry_id,a.cust_id,COALESCE(a.amount,b.amount,0) AS amount
FROM t1 a
LEFT JOIN (SELECT store_id AS store_id_2,industry_id AS industry_id_2,cust_id AS cust_id_2,amount FROM t2) b
ON a.cust_id=b.cust_id_2 AND a.industry_id=b.industry_id_2;
此查询结果:
store_id industry_id cust_id amount
1 100 1000 1.00
2 100 1000 2.05
3 100 1000 3.15
4 200 2000 5.00
5 200 2000 6.00
解决方法
对于此数据集union all
似乎足够好:
select store_id,industry_id,cust_id,amount from t1
union all
select store_id,amount from t2
我推测两个表中可能会出现相同的商店/行业/客户元组,并且您只希望结果中的一行包含总计相应的金额。如果是这样,您可能会对full join
感兴趣:
select
coalesce(t1.store_id,t2.store_id) store_id,coalesce(t1.industry_id,t2.industry_id) industry_id,coalesce(t1.cust_id,t2.cust_id) cust_id,coalesce(t1.amount,0) + coalesce(t2.amount,0) amount
from t1
full join t2
on t2.store = t1.store and t2.industry = t1.industry and t2.cust_id = t1.cust_id