Domanda

Hello i need help here...

my query shows the folllowing result:

Id      name           color    Version
1       leather        black      1
1       leather        brown      2
2       suede          brown      1
3       cloth          green      1
3       cloth          blue       2

i want to display the following:

Id      name           color    Color_2    
1       leather        black      brown     
2       suede          brown      
3       cloth          green      blue

query is simple currently

SELECT ID, NAME, COLOR,VERSION
FROM table1,table2  
WHERE table1.ID = table2.ID 
AND id in 
    (SELECT ID 
    FROM table1,table2 
    WHERE table1.ID = table2.ID  
    AND VERSION in ('1'))
AND VERSION in ('1','2')
È stato utile?

Soluzione

A simple one (if you know at design time the maximum number of colors you could possibly have)

drop table my_test;

create table my_test (
  id          number,
  name        varchar2(32),
  color       varchar2(32),
  version     number);

insert into my_test values(1,'leather','black',1);
insert into my_test values(1,'leather','brown',2);
insert into my_test values(2,'suede','brown',1);
insert into my_test values(3,'cloth','green',1);
insert into my_test values(3,'cloth','blue ',2);

set linesize 200
select min(id) id,
       name,
       max(decode(version,1,color,null)) color,
       max(decode(version,2,color,null)) color_2
  from my_test
 group by name
 order by 1;

        ID NAME       COLOR      COLOR_2   
---------- ---------- ---------- ----------
         1 leather    black      brown     
         2 suede      brown                
         3 cloth      green      blue      

3 rows selected.

This will work with any Oracle database version. Depending on the version you use, look at the LISTAGG, WM_CONCAT and the like (here)

Altri suggerimenti

You're a little all over the place with your database type...is it mysql or oracle? I'm guessing oracle by your select statement anyway. I'm using 'join' based syntax, I find it easier to read than what you have here. Take a select statement with version 1 and left join it to a select statement with version 2. If there is a version three, put another join in there.

select a.id, a.name, a.colour, b.colour
from (select * from table1 where version = 1) a
left join (select * from table1 where version = 2) b
 on a.id = b.id

(this assumes version 1 always exists and there can't be a version 2 without a version 1)

let me reframe the question -- it is oracle.. it all from the same table the color also ... SELECT tabble1.ID, table1.NAME, table1.COLOR,table1.VERSION FROM table1,table2
WHERE table1.ID = table2.ID AND id in (SELECT ID FROM table1,table2 WHERE table1.ID = table2.ID
AND VERSION in ('1')) AND VERSION in ('1','2')

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top