我有以下資料集:
表格1

2021 年是我的基準年,我想知道從 2021 年開始的這些產品中,哪些也發生在 2022 年。因此,只有當一個產品在 2021 年有 Contract_start 時,我才想在 2022 年也使用 Contract_start 拉同樣的產品。
因此,我的輸出應如下所示

我嘗試了以下查詢。此方法未能包括產品 C 的所有四個實體,而是僅提取 2021 年的一個產品 C 和 2022 年的一個產品 C。如何修復此查詢,以便從 2021 年開始的所有產品都包含在正確的行數中,而不會導致重復對于 2022 年的產品?
with values_2021 as
( select distinct
CUSTOMER_NUMBER||PRODUCT as productcust
from table1
where substr(CONTRACT_START,1,4) = '2021'
)
SELECT distinct
CUSTOMER_NUMBER,
TOTAL_DOLLARS,
PRODUCT,
CONTRACT_START,
CONTRACT_END
FROM table1
join values_2021 on (table1.CUSTOMER_NUMBER||table1.PRODUCT) = values_2021.productcust
where CONTRACT_START >= ('20210101')
uj5u.com熱心網友回復:
不確定這對您的資料的性能如何,但希望它能為您指明正確的方向。
SELECT b.*
FROM (SELECT DISTINCT customer_number,
product
FROM table1
WHERE Substr(contract_start, 1, 4) = '2021') a
inner join table1 b
ON a.customer_number = b.customer_number
AND a.product = b.product
AND b.contract_start >= ( '20210101' )
uj5u.com熱心網友回復:
一種選擇是使用公用表運算式擴展您正在執行的操作。為 2022 年創建另一個 CTE。然后,將兩者連接回主表。正如 jarlh 所提到的,連接兩列而不是使用字串連接。如果在 contract_start 上存在索引,則將 SUBSTR 切換為 LIKE 可以允許使用索引。
WITH values_2021 AS (
SELECT customer_number
,product
FROM table1
WHERE contract_start LIKE '2021%'
GROUP BY customer_number
,product
),values_2022 AS (
SELECT customer_number
,product
FROM table1
WHERE contract_start LIKE '2022%'
GROUP BY customer_number
,product
)
SELECT t1.customer_number
,t1.total_dollars
,t1.product
,t1.contract_start
,t1.contract_end
FROM table1 t1
JOIN values_2021 v2021 ON ( t1.customer_number = v2021.customer_number
AND t1.product = v2021.product )
JOIN values_2022 v2022 ON ( t1.customer_number = v2022.customer_number
AND t1.product = v2022.product );
uj5u.com熱心網友回復:
最簡單的方式就是問題中所說的—— 2021年開始的產品也出現在2022年。使用問題中的資料,您可以嘗試以下操作:
Select *
From table_1
Where PRODUCT IN (Select PRODUCT From table_1 Where Substr(CONTRACT_START, 1, 4) = '2021') And -- products 2021
PRODUCT IN (Select PRODUCT From table_1 Where Substr(CONTRACT_START, 1, 4) = '2022') And -- products 2022
SubStr(CONTRACT_START, 1, 4) IN('2021', '2022')
...結果為
| 顧客 | TOTAL_DOLLARS | 產品 | CONTRACT_START | CONTRACT_END |
|---|---|---|---|---|
| 1 | 50 | 一個 | 20210614 | 20220613 |
| 1 | 60 | 一個 | 20220614 | 20230613 |
| 1 | 800 | 乙 | 20211031 | 20221030 |
| 1 | 900 | 乙 | 20221031 | 20231030 |
| 1 | 600 | C | 20210614 | 20220613 |
| 1 | 0 | C | 20210707 | 20220706 |
| 1 | 646 | C | 20220614 | 20220711 |
| 1 | 0 | C | 20220707 | 20230706 |
問候...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/522706.html
標籤:sql甲骨文
