A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Hi @Shanvitha ,
Please refer to:
CREATE TABLE A (NAME NVARCHAR(10), code BIGINT)
INSERT INTO A (NAME, CODE)
VALUES ('INDIA', 1000000000001);
INSERT INTO A (NAME, CODE)
VALUES ('RSA', 1000000000011);
INSERT INTO A (NAME, CODE)
VALUES ('AMERICA', 1000000000015);
CREATE TABLE Tenant ([CODE] VARCHAR(13), [COLOR] VARCHAR(5), [TYPE] VARCHAR(2));
INSERT INTO Tenant ([CODE], [COLOR], [TYPE])
VALUES ('1000000000001', 'GREEN', 'TN'), ('1000000000018', 'RED', 'TN'), ('1000000000001', 'PIN', 'TN'), (NULL, 'BLACK', 'SS');
select a.[Name],a.Code,IIF(a.Code in (select Code from Tenant),t.[COLOR],(select [COLOR] from Tenant where [TYPE]='SS'))COLOR
from A a
left join Tenant t
on a.Code=t.Code
drop table A
drop table Tenant
You can also use case when:
select a.[Name],a.Code,case when a.Code in (select Code from Tenant) then t.[COLOR]
else (select [COLOR] from Tenant where [TYPE]='SS') end COLOR
from A a
left join Tenant t
on a.Code=t.Code
The code 1000000000001 has two colors. If you randomly choose one to return, please refer to:
with cte
as(select a.[Name],a.Code,case when a.Code in (select Code from Tenant) then t.[COLOR]
else (select [COLOR] from Tenant where [TYPE]='SS') end COLOR
from A a
left join Tenant t
on a.Code=t.Code)
,cte2 as(select*,row_number() over(partition by [Name],Code order by Code) rn from cte)
select [Name],Code,COLOR from cte2 where rn<2
order by Code
If you have any question, please feel free to let me know.
If the response is helpful, please click "Accept Answer" and upvote it.
Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


