[英]Select a new column based on values of two column from two tables with null if no data is present
如果不存在數據,如何根據兩個表中兩列的值 select 創建一個新列 null。
我有兩張桌子
table1 與 column1 和 table2 與 column2。 我需要 select 來自 column3 中這兩列的數據(column3 將是 table1 的一部分),其方式如下:
column1 column2 column3
------- ------- -------
1 2 null
2 3 present
3 present
4 null
如果column2 的值出現在 column1 中
=> 我需要能夠在 column3 中分配一個字符串(可以說“存在”)
否則column3 中的值應為 null
目前我正在使用 join 但我無法將 null 部分分配給 column3
提前致謝。
create table table1(column1 int);
create table table2(column2 int);
insert into table1 values(1);
insert into table1 values(2);
insert into table1 values(3);
insert into table1 values(4);
insert into table2 values(2);
insert into table2 values(3);
詢問:
select column1, (case when column2 is not null then 'Present' else Null end) Column3
from table1 left join table2 on column1=column2
Output:
專欄 1 | 專欄3 |
---|---|
1個 | null |
2個 | 展示 |
3個 | 展示 |
4個 | null |
db<> 在這里擺弄
如果 col1 和 col2 沒有重復值,您可以使用:
select t1.col1 , case when t2.col2 is not null then 'present' else null end
from table1 t1
left join table2 t2
on t1.col1 = t2.col2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.