【发布时间】:2019-01-20 10:26:01
【问题描述】:
我有以下两张表,我想加入他们做第三张表
表 A
customer_id first_order_date last_order_date
123 2017-04-06 2018-07-30
456 2017-08-07 2018-07-24
789 2018-03-13 2018-07-03
表 B
order_id customer_id order_created_at num_of_products num_of_x_products
abc 123 2017-04-06 4 2
xyz 123 2018-07-30 5 3
def 456 2017-08-07 6 6
lmn 456 2018-07-24 4 1
ghi 789 2018-03-13 6 5
pqr 789 2018-07-03 3 3
我想加入这两个表并创建第三个看起来像的表。我该怎么做?
customer_id first_order_date last_order_date first_num_of_products last_num_of_products
123 2017-04-06 2018-07-30 4 5
456 2017-08-07 2018-07-24 6 4
这是我的代码
SELECT
"cus".customer_id
,"fo".order_created_at as first_order_created_at
,"fo".order_id as first_order_id
,"fo".number_of_products as first_number_of_products
,"lo".order_created_at as last_order_created_at
,"lo".order_id as last_order_id
,"lo".number_of_products as last_number_of_products
FROM table_a AS "cus"
INNER JOIN table_b AS "fo"
ON "cus".customer_id = "fo".customer_id
AND "cus".first_order_date = "fo".order_created_at
INNER JOIN table_b AS "lo"
ON "cus".customer_id = "lo".customer_id
AND "cus".last_order_date = "lo".order_created_at
【问题讨论】:
-
你研究过连接并尝试写一个吗?
-
@dfundako 我有,似乎我必须将第一张桌子加入第二张桌子两次,但由于某种原因我没有得到任何结果。希望得到一些帮助!
-
分享你写的代码。
-
从你的样本数据和期望来看,我认为你不需要使用
JOIN你只能写一个查询。 -
@dfundako 问题已包含在代码中
标签: sql snowflake-cloud-data-platform