我有這樣的表1:
| ID | 國家 |
|---|---|
| 1 | 德國 |
| 1 | 美國 |
| 1 | 日本 |
| 2 | 法國 |
表2這樣
| ID | 顏色 |
|---|---|
| 1 | 綠色的 |
| 2 | 紅色的 |
| 2 | 黃色的 |
是否可以使用 SQL 陳述句得到這樣的結果?:
| ID | 國家 | 顏色 |
|---|---|---|
| 1 | 德國 | 綠色的 |
| 1 | 美國 | |
| 1 | 日本 | |
| 2 | 法國 | 紅色的 |
| 2 | 黃色的 |
這意味著,如果 id 1 有 3 個國家和 1 種顏色 --> 結果應該以任何順序只回傳 3 個國家和 1 種顏色(并且顏色可以與任何國家在同一行)。一般來說,如果 id 1 有 m 個國家和 n 個顏色 --> 結果應該只回傳 m 個國家和 n 個顏色?非常感謝<3
注意:我使用的是 Oracle 資料庫
uj5u.com熱心網友回復:
您可以為每個 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
uj5u.com熱心網友回復:
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
小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/427752.html
上一篇:非規范化表上的SQL查詢
