J'ai une table:
Table1
row_id var1 var2 1 123 456 2 665t dsfs 3 sfs sf
Voici la sortie:
Table2
row_id var var_val 1 Test 1 123 1 Test 2 456 1 Test 3 789 1 Test 4 1234 2 Test 1 665t 2 Test 2 dsfs 2 Test 3 df 2 Test 4 sfd 3 Test 1 sfs 3 Test 2 sf 3 Test 3 sdfs 3 Test 4 sfsd
Existe-t-il un moyen d'utiliser le pivot ou un moyen d'extraire la variable pour chaque row_id de la table1 comme ci-dessus?
3 Réponses :
Vous pouvez utiliser une agrégation conditionnelle ou une join :
select t11.row_id, t11.var, t12.var
from table1 t11 join
table1 t12
on t11.row_id = t12.row_id and
t11.var = 'Test 1' and
t12.var = 'Test 2'
Existe-t-il un moyen d'utiliser le pivot ...?
Sûr:
select * from table1 pivot (max(var_val) for var in ('Test 1' var1, 'Test 2' var2))
Vous pouvez utiliser ensemble la fonction d'analyse de fenêtre sous-requêtes corrélées et row_number ()
with table1(row_id, var, var_val) as
(
select 1,'Test 1','123' from dual union all
select 1,'Test 2','456' from dual union all
select 1,'Test 3','789' from dual union all
select 1,'Test 4','1234' from dual union all
select 2,'Test 1','665t' from dual union all
select 2,'Test 2','dsfs' from dual union all
select 2,'Test 3','df' from dual union all
select 2,'Test 4','sfd' from dual union all
select 3,'Test 1','sfs' from dual union all
select 3,'Test 2','sf' from dual union all
select 3,'Test 3','sdfs' from dual union all
select 3,'Test 4','sfsd' from dual
), t2 as
(
select t.*, row_number() over (partition by var order by row_id) as rn
from table1 t
)
select distinct row_id,
(select var_val
from table1 t2
where t2.var = 'Test 1'
and t2.row_id = rn) as var1,
(select var_val
from table1 t2
where t2.var = 'Test 2'
and t2.row_id = rn) as var2
from t2
order by row_id
ROW_ID VAR1 VAR2
------ ---- ----
1 123 456
2 665t dsfs
3 sfs sf
Modifiez votre question et affichez les résultats souhaités.
table2 est la sortie
Que contient la colonne var1 et var2? comment il est calculé?