[英]Select all records from one table not in another table based on a condition
[英]Select one value from a table and only one match from another table based on a condition
我有兩個表作為這個例子
- 新APP
活動ID | 活動名稱 | 創建於 |
---|---|---|
123456 | 名稱1 | 2022-07-07 17:59:24.453 |
123333 | 名稱2 | 2022-07-07 17:59:24.453 |
123123 | 名稱3 | 2022-07-01 17:59:24.453 |
123123 | 名稱4 | 2022-07-01 17:59:24.453 |
-舊APP
活動ID | 活動名稱 | 創建於 |
---|---|---|
123123.123123.0000 | 姓名 | 2022-07-01 17:59:24.453 |
123123.123123.1111 | 姓名 | 2022-07-01 17:59:24.453 |
123123.123123.1112 | 姓名 | 2022-07-01 17:59:24.453 |
我想找到一種方法,只從舊應用程序中獲取一條匹配記錄,從我嘗試過的新應用程序中獲取一條匹配記錄
with cte as ( select *,row_number() over( partition by ActivityID order by ActivityID ) rn
from OldApp),
cte2, select * row_number() over( partition by left(ActivityID,6) order by left(ActivityID,6) rn
from NewApp
)
select * from cte
right outer join cte2 on (cte.ActivityID = cte2.ActivityID and cte.rn=1 and cte2.rn=1)
但是結果仍然顯示 cte2 中行號列的多個值我在這里缺少什么?
您需要在 cte 中切換表名並與 activityID 的LEFT
連接以僅獲取第 1 行,但右連接仍會顯示其他行
with cte as ( select *,row_number() over( partition by ActivityID order by ActivityID ) rn from NewApp), cte2 as ( select *,row_number() over( partition by left(ActivityID,6) order by left(ActivityID,6) ) rn from OldApp ) select * from cte right outer join cte2 on (left(cte2.ActivityID,6) = cte.ActivityID and cte.rn=1 and cte2.rn=1)
活動ID | 活動名稱 | 創建於 | rn | 活動ID | 活動名稱 | 創建於 | rn ---------: |:------------ |:---------- | ---: |:----------------- |:------------ |:------------ ---------- | -:123123 | 名稱3 | 2022-07-01 17:59:24.453 | 1 | 123123.123123.0000 | 姓名 | 2022-07-01 17:59:24.453 | 1 null | null | null | null | 123123.123123.1111 | 姓名 | 2022-07-01 17:59:24.453 | 2 null | null | null | null | 123123.123123.1112 | 姓名 | 2022-07-01 17:59:24.453 | 3
db<> 在這里擺弄
with new as (
select *,
row_number() over (partition by ActivityID order by CreatedOn, ActivityName) rn
from NewApp
)
select * from OldApp old left outer join new
on left(old.ActivityID, 6) = new.ActivityID and new.rn = 1;
https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=a2852289ed3a12eab0868542706cd895
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.