Oracle-SQL 加入重复的列但避免重复的行
Oracle-SQL Join on Duplicate columns but avoid Duplicate rows
我有 table 1 个这样的:
id
Country
1
Germany
1
USA
1
Japan
2
France
Table 2 个这样
id
Color
1
Green
2
Red
2
Yellow
是否可以使用 SQL 语句得到这样的结果?:
id
Country
Color
1
Germany
Green
1
USA
1
Japan
2
France
Red
2
Yellow
这意味着,如果 id 1 有 3 个国家和 1 种颜色 --> 结果应该 return 只有 3 个国家和 1 种颜色,顺序任意(并且颜色可以与任何国家在同一行).一般来说,如果 id 1 有 m 个国家和 n 种颜色 --> 结果应该 return 只有 m 个国家和 n 种颜色?
非常感谢 <3
注意:我使用的是 Oracle 数据库
您可以对每个 ID 的国家和颜色进行编号,然后对 ID 和该编号使用完全外部联接:
with cntr as
(
select id, row_number() over (partition by id order by country) as subid, country
from country
)
, clr as
(
select id, row_number() over (partition by id order by color) as subid, color
from color
)
select id, cntr.country, clr.color
from cntr full outer join clr using (id, subid)
order by id, subid nulls last;
演示:https://dbfiddle.uk/?rdbms=oracle_18&fiddle=e74ece8cb4571d7998014f8c55bd8d7a
with src as (
select n.id,n.country,l.color,
(select count(id)-1
from countries where id=n.id) total_countries
,(
select count(id)-1
from colors where id=l.id
) total_colors
from countries n
inner join colors l
on n.id = l.id
)
select
id,
country,
lag(color, total_countries) over (partition by id order by color) color
from
src
where total_countries > 0
union all
select
id,
lag(country, total_colors) over (partition by id order by country) country
,color
from
src
where total_colors > 0
order by id, country nulls last, color nulls last
我有 table 1 个这样的:
id | Country |
---|---|
1 | Germany |
1 | USA |
1 | Japan |
2 | France |
Table 2 个这样
id | Color |
---|---|
1 | Green |
2 | Red |
2 | Yellow |
是否可以使用 SQL 语句得到这样的结果?:
id | Country | Color |
---|---|---|
1 | Germany | Green |
1 | USA | |
1 | Japan | |
2 | France | Red |
2 | Yellow |
这意味着,如果 id 1 有 3 个国家和 1 种颜色 --> 结果应该 return 只有 3 个国家和 1 种颜色,顺序任意(并且颜色可以与任何国家在同一行).一般来说,如果 id 1 有 m 个国家和 n 种颜色 --> 结果应该 return 只有 m 个国家和 n 种颜色? 非常感谢 <3
注意:我使用的是 Oracle 数据库
您可以对每个 ID 的国家和颜色进行编号,然后对 ID 和该编号使用完全外部联接:
with cntr as
(
select id, row_number() over (partition by id order by country) as subid, country
from country
)
, clr as
(
select id, row_number() over (partition by id order by color) as subid, color
from color
)
select id, cntr.country, clr.color
from cntr full outer join clr using (id, subid)
order by id, subid nulls last;
演示:https://dbfiddle.uk/?rdbms=oracle_18&fiddle=e74ece8cb4571d7998014f8c55bd8d7a
with src as (
select n.id,n.country,l.color,
(select count(id)-1
from countries where id=n.id) total_countries
,(
select count(id)-1
from colors where id=l.id
) total_colors
from countries n
inner join colors l
on n.id = l.id
)
select
id,
country,
lag(color, total_countries) over (partition by id order by color) color
from
src
where total_countries > 0
union all
select
id,
lag(country, total_colors) over (partition by id order by country) country
,color
from
src
where total_colors > 0
order by id, country nulls last, color nulls last