故事:
我需要查看每个name_id
,如果它们具有至少一个落入continent_id category
的值。
所以name_id
1,他在country_id
1,2,3中至少有一个continent_id
。name_id
2在country_id
1,3中至少有一个continent_id
。
数据:
+---------+------------+
| name_id | country_id |
+---------+------------+
| 1 | 10 |
| 1 | 11 |
| 1 | 12 |
| 1 | 20 |
| 1 | 21 |
| 1 | 30 |
| 2 | 10 |
| 2 | 30 |
+---------+------------+
+------------+--------------+
| country_id | continent_id |
+------------+--------------+
| 10 | 1 |
| 11 | 1 |
| 12 | 1 |
| 20 | 2 |
| 21 | 2 |
| 30 | 3 |
+------------+--------------+
所需的输出:
+---------+-------------+-------------+-------------+
| name_id | continent_1 | continent_2 | continent_3 |
+---------+-------------+-------------+-------------+
| 1 | YES | YES | YES |
| 2 | YES | NO | YES |
+---------+-------------+-------------+-------------+
目标:
我需要一个表格,对于每个name_id
,每一个continent_id
的分组都有一个是或否的标志。
我尝试过的事情:
我开始在每个大洲进行3次左联接,并使用case语句,但想知道如果实际表包含数百万个数据,是否有更有效的方法。
小提琴:
create table #t1 (name_id int,country_id varchar(20))
insert into #t1 values
(1,10),
(1,11),
(1,12),
(1,20),
(1,21),
(1,30),
(2,10),
(2,30)
create table #t2 (country_id int,continent_id varchar(20))
insert into #t2 values
(10,1),
(11,1),
(12,1),
(20,2),
(21,2),
(30,3)
select
n.name_id,
case when max(case when c.continent_id = 1 then 1 end) = 1
then 'YES'
else 'NO'
end continent_1,
case when max(case when c.continent_id = 2 then 1 end) = 1
then 'YES'
else 'NO'
end continent_2,
case when max(case when c.continent_id = 3 then 1 end) = 1
then 'YES'
else 'NO'
end continent_3
from #t1 n
left join #t2 c on c.country_id = n.country_id
group by n.name_id
Demo on DB Fiddle:name_id | continent_1 | continent_2 | continent_3------:| :---------- | :---------- | :----------1 |是的是的是2 |是的否|是