- Создать первую таблицу и загрузить данные
create table #t1 (id int, category varchar(30) )
insert into #t1 (id,category)
values (1, 'soap')
insert into #t1 (id,category)
values (2, 'grocery')
insert into #t1 (id,category)
values (3, 'snacks')
insert into #t1 (id,category)
values (4, 'vegetables')
insert into #t1 (id,category)
values (5, 'dairy')
insert into #t1 (id,category)
values (6, 'clothes')
insert into #t1 (id,category)
values (7, 'books')
insert into #t1 (id,category)
values (8, 'shoes')
- Создать вторую таблицу и загрузить данные
create table #t2 (id int, parent_cat varchar(30) , code varchar(10))
insert into #t2 (id, parent_cat, code)
values(1,'soap','SHP')
insert into #t2 (id, parent_cat, code)
values(2,'clothes','CLTH')
insert into #t2 (id, parent_cat, code)
values(3,'snacks','SNCK')
insert into #t2 (id, parent_cat, code)
values(4,'books','SHP')
insert into #t2 (id, parent_cat, code)
values(5,'others','OTH')
- Окончательный запрос
SELECT #t1.id, #t1.category, isnull(#t2.code, 'OTH') code from #t1
LEft join #t2 on #t1.category = #t2.parent_cat
- Выход
