为两个商店中存在的每个 product_id 显示 purchase_date
Display purchase_date for each product_id that exists in both stores
我想为每个 product_id 显示两个商店 中商店 A 和商店 B 中的 purchase_date分开两列,而不是按行显示。
Main_table
product_id store purchase_date
44343 A 2019-01-01
44343 B 2019-01-03
23234 A 2019-02-01
23234 B 2019-02-02
55433 A 2019-01-15
55433 B 2019-01-16
22324 A 2019-01-01
74456 B 2019-01-01
Output_table
product_id purchase_date_storeA purchase_date_storeB
44343 2019-01-01 2019-01-03
23234 2019-02-01 2019-02-02
55433 2019-01-15 2019-01-16
这是我迄今为止尝试过的方法,但没有成功:
select
purchase_date,
product_id,
case when store = 'A' then purchase_date end as purchase_date_storeA,
case when store = 'B.' then purchase_date end as purchase_date_storeB
from main_table
使用GROUP BY
和HAVING
如下:
select
product_id,
max(case when store = 'A' then purchase_date end) as purchase_date_storeA,
max(case when store = 'B' then purchase_date end) as purchase_date_storeB
from main_table
where store in ('A','B')
group by product_id
having count(distinct store) = 2
我想为每个 product_id 显示两个商店 中商店 A 和商店 B 中的 purchase_date分开两列,而不是按行显示。
Main_table
product_id store purchase_date
44343 A 2019-01-01
44343 B 2019-01-03
23234 A 2019-02-01
23234 B 2019-02-02
55433 A 2019-01-15
55433 B 2019-01-16
22324 A 2019-01-01
74456 B 2019-01-01
Output_table
product_id purchase_date_storeA purchase_date_storeB
44343 2019-01-01 2019-01-03
23234 2019-02-01 2019-02-02
55433 2019-01-15 2019-01-16
这是我迄今为止尝试过的方法,但没有成功:
select
purchase_date,
product_id,
case when store = 'A' then purchase_date end as purchase_date_storeA,
case when store = 'B.' then purchase_date end as purchase_date_storeB
from main_table
使用GROUP BY
和HAVING
如下:
select
product_id,
max(case when store = 'A' then purchase_date end) as purchase_date_storeA,
max(case when store = 'B' then purchase_date end) as purchase_date_storeB
from main_table
where store in ('A','B')
group by product_id
having count(distinct store) = 2