[英]How to pull unique SQL values from two different tables into one column?
我有兩個表,每個表都有不明確的 ID、產品和銷售日期。 我想要一個組合表,其中行是不同的 ID,列是每種產品的最早銷售日期。
這些表如下所示:
表格1
會員ID | 產品 | 銷售日期 |
---|---|---|
1個 | A | 01/01/2021 |
1個 | A | 02/01/2021 |
2個 | A | 01/01/2021 |
3個 | A | 02/02/2021 |
表_2
會員ID | 產品 | 銷售日期 |
---|---|---|
1個 | 乙 | 04/01/2021 |
1個 | 乙 | 05/01/2021 |
2個 | 乙 | 04/01/2021 |
3個 | 乙 | 03/01/2021 |
我想要的茶幾是:
合並表
會員ID | Product_A_earliest_date | Product_B_earliest_date |
---|---|---|
1個 | 01/01/2021 | 04/01/2021 |
2個 | 01/01/2021 | 04/01/2021 |
3個 | 02/01/2021 | 03/01/2021 |
我嘗試了以下代碼來合並表:
create table merged_table as
select member_id, min(a.sales_date) as Product_A_earliest_date, min(b.sales_date) as Product_B_earliest_date from(
select member_id from table_1 as a
UNION
select member_id from table_2 as b);
但這提供了“EOF 缺失”錯誤。 我是否錯誤地使用了 UNION function?
當語句不完整時,我們通常會missing at EOF
。
您的 sql 聲明存在一些問題:
table_1
的別名a
和用於table_b
的別名b
將不存在於用於創建聯合的子查詢之外min
和非聚合列member_id
而 group by 子句中沒有member_id
。您可以嘗試以下查詢
SELECT
Member_ID,
MIN(
CASE WHEN Product='A' THEN Sales_Date END
) as Product_A_earliest_date,
MIN(
CASE WHEN Product='B' THEN Sales_Date END
) as Product_B_earliest_date
FROM (
SELECT Member_ID, Product, Sales_Date FROM table_1
UNION ALL
SELECT Member_ID, Product, Sales_Date FROM table_2
) t
GROUP BY Member_ID
ORDER BY Member_ID
會員ID | product_a_earliest_date | product_b_earliest_date |
---|---|---|
1個 | 2021-01-01 | 2021-04-01 |
2個 | 2021-01-01 | 2021-04-01 |
3個 | 2021-02-02 | 2021-03-01 |
如果這對你有用,請告訴我。
假設 sql 服務器或其他支持 ctes 的引擎...
第一個挑戰是獲取所有 ID……不可能每個銷售人員都銷售這兩種產品
一旦你有了它,它就相當簡單了。 我沒有對此進行測試,但這是方法。
;with ids as ( select distinct member_Id from table_1
union
select distinct member_id from table_2
)
, uniqueIds as ( select distinct member_id from ids)
;with t1 as ( select member_id, product, min(sales_date) [sales_date]
from Table_1
group by member_id,product)
, t2 as ( select member_id, product, min(sales_date) [sales_date]
from Table_2
group by member_id,product)
select ui.member_Id, t1.salesDate [EarlyDate_a], t2.salesDate [earlydate_b]
from uniqueIds ui
left join t1_ on ui.memberId = t1.memberId
left join t2_ on ui.memberId = t2.memberId
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.