-2

J'ai 2 tablesCompliqué Sql requête de jointure avec une condition pour obtenir un de la colonne

Tableau 1:

Id | product | price 
---+---------+------ 
1 | A | 5 
1 | B | 3 
1 | C | 6 

Tableau 2:

Id | prod | subprod 
---+------+-------- 
1 | A | xxxx 
1 | A | yyyy 
1 | A | zzzz 

Mon tableau de résultats devrait avoir toutes les 3 lignes à partir de table2 avec une nouvelle colonne appelée prix (qui sera calculée valeur de table1)

table résultat devrait ressembler à

Id|prod|subprod|price 
--+----+-------+----- 
1 | A | xxxx |(if subprod = xxxx in table 2 then this should have price of A from table 1) 
1 | A | yyyy |(if subprod = yyyy in table 2, then if price of B is greater than price of C then the value should be price of B else 0) 
1 | A | zzzz |(if subprod = zzzz in table 2, then if price of B is less than price of C then the value should be price of C-B else 0) 

+0

voulez-vous l'ensemble si déclaration dans votre sortie, ou voulez-vous la solution à la déclaration if? aussi qu'avez-vous essayé jusqu'ici? posez votre question – RealCheeseLord

+0

ressemble à des devoirs –

+0

@RealCheeseLord J'ai créé une fonction avec tout ce dur codé et en l'appelant à chaque fois dans la requête – user2954417

Répondre

0

Essayez ceci:

select distinct tab_2.*,case when tab_2.subprod ='xxxx' then (select tab_1.price from tab_1 where product='A') 
when tab_2.subprod ='yyyy' then CASE WHEN (select price from tab_1 where product='B') > (select price from tab_1 where product='C') THEN (select price from tab_1 where product='B') else 0 end 
when tab_2.subprod ='zzzz' then CASE WHEN (select price from tab_1 where product='B') < (select price from tab_1 where product='C') THEN (select price from tab_1 where product='C') - (select price from tab_1 where product='B') else 0 end 
END AS price 
from tab_1,tab_2 
where tab_1.Id =tab_2.id 

Sortie: -

id prod subprod  price 
1 A  xxxx  5 
1 A  yyyy  0 
1 A  zzzz  3 

EDIT:

select distinct tab_2.*,case when tab_2.subprod ='xxxx' then (select tab_1.price from tab_1 where product='A') 
when tab_2.subprod ='yyyy' then CASE WHEN b.price > c.price THEN b.price else 0 end 
when tab_2.subprod ='zzzz' then CASE WHEN b.price < c.price THEN c.price - b.price else 0 end 
END AS price 
from tab_1,tab_2,(select id,price from tab_1 where product='B') b,(select id,price from tab_1 where product='C')c 
where tab_1.Id =tab_2.id 
and b.id =tab_2.id 
and c.Id =tab_2.id 
+0

Cela fonctionne ... est-il possible de mieux utiliser les instructions cAse? – user2954417

+0

vérifier la requête modifiée – Anagha