我有三個表:#T、#T1、#Maintable,我將為其附加相應的 DDL。
Create table #T ( id int , reason varchar (50));
insert into #T Values (1,'Texas for live music');
insert into #T Values (1,'Texas for BBQ');
insert into #T Values (2,'Wisconsin for dairy products');
insert into #T Values (2,'Wisconsin for Rock');
insert into #T Values (2,'Wisconsin for Bird');
insert into #T Values (3,'North Carolina for Pepsi');
insert into #T Values (4,'Missouri for Forest');
insert into #T Values (5,'Oklohoma for cowboy');
insert into #T Values (5,'Oklohoma for Native Americans');
insert into #T Values (5,'Oklohoma for oil and gas');
Create table #T1 ( id int , reason varchar (50));
insert into #T1 Values (1,'Texas for live music,BBQ');
insert into #T1 Values (2,'Wisconsin for dairy products, rock,bird');
insert into #T1 Values (3,'North Carolina for Pepsi');
insert into #T1 Values (4,'Missouri for Forest');
insert into #T1 Values (5,'Oklohoma for Native Americans,oil and gas');
Create table #MainTable (id int, State varchar(20),Capital varchar(30),Governer varchar(30));
Insert into #Maintable values (1,'Texas','Austin','A');
Insert into #Maintable values (2,'Wisconsin','Madison','B');
Insert into #Maintable values (3,'North Carolina','Releigh','C');
Insert into #Maintable values (4,'Missouri','Jefferson City','D');
Insert into #Maintable values (5,'Oklohoma','Oklohoma city','E');
預期產出
| ID | 原因 | 狀態 | 首都 | 州長 |
|---|---|---|---|---|
| 1 | 德克薩斯州的現場音樂,燒烤 | 德克薩斯州 | 奧斯汀 | 一個 |
| 2 | 威斯康星州的乳制品、巖石、鳥類 | 威斯康星州 | 麥迪遜 | 乙 |
| 3 | 百事可樂的北卡羅來納州 | 北卡羅來納 | 雷利 | C |
| 4 | 密蘇里森林 | 密蘇里州 | 杰斐遜城 | D |
| 5 | 俄克拉荷馬州的美洲原住民、石油和天然氣 | 俄克拉荷馬州 | 俄克拉荷馬城 | 乙 |
我有幾個表,根據我將從表#T 中過濾記錄并與其他表連接以獲得更多列的條件,但在 cte 的幫助下,我無法過濾。如果第一個表 #T 有多個 Id,那么我們將使用另一個表 #T1 的原因。如果它只有一個 Id,那么我們將使用表 #T 中的原因,最后,我們將與 #main 表連接以獲取其他記錄。我添加了一個描述更多的影像。非常感謝您的幫助。我們可以測驗的所有臨時表
場景是:
- 如果原因在#T 表中出現多次,請使用#T1 表
- 如果原因在#T 表中僅出現一次,則僅使用#T,這是第一個表
這是我的編碼嘗試:
with cte as (
select *, ROW_NUMBER() over (partition by id order by id) rn
from #T
)
select mt.id, state, capital, Governer,
case when c.rn > 1
then #t1.reason
else c.reason
end as reason
from cte c
join #t1 on c.id = #t1.id
join #maintable mt on c.id = mt.id
我得到了更多的結果,我期望只有 5 條記錄。我想我的 row_number 中存在一些問題。幫助表示贊賞。
uj5u.com熱心網友回復:
您應該首先從表“ #T ”中提取每個 ID 的排名值。然后您可以使用該COALESCE功能結合LEFT JOIN操作來解決您的問題:
WITH #T_ranked AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY id ORDER BY reason) AS rn
FROM #T
)
SELECT m.id,
COALESCE(#T1.reason, #T_ranked.reason) AS Reason,
m.State,
m.Capital,
m.Governer
FROM #Maintable m
LEFT JOIN #T1 ON m.id = #T1.id
LEFT JOIN #T_ranked ON m.id = #T_ranked.id AND #T_ranked.rn = 1
這些LEFT JOIN操作將保留您在“ MainTable ”中的ID,而該COALESCE函式將使第一個非空引數成為“ Reason ”新欄位的值,在特定情況下它將檢查是否“ #T1.Reason " 為空,如果是則將分配" #T2.Reason "。在“ #T1.Reason ”中具有現有對應方的“ #T.Reason ”中的值將永遠不會以這種方式被選擇。
在此處查看演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/514555.html
下一篇:如何替換正則運算式?
