2016-05-12 79 views
0

嗨,我有以下表如何选择特定数量的特定数量的ID列?

table_A 

ID NAME PRICE DATE 
123 JOHN 22  1/1/2010 
234 KING 50  5/10/2009 
345 JACK 400  30/11/210 

进出料放:

我要挑第一列的第二ID和第三ID第三列拳头ID和第二列。

ID VALUES 
123 JOHN 
234 50 
345 30/11/2010 

我的查询:

select ID, NAME 
from table_A 
where ID = 123 

union all 

select ID, PRICE 
from table_A 
where ID = 234 

union all 

select ID, DATE 
from table_A 
where ID = 345; 

两个原因,我的查询是不正确的: 1)它不工会不同的数据类型 2)其难度输入所有ID等,很多工会

需要更好的查询的话,它会自动挑选第一列和第二列第二笔贷款的第一笔贷款...

+0

究竟是你想怎么办? –

+0

如何将每列转换为字符串,联合应该工作然后 – Stivan

+0

不能我们做一些像使用循环。 – Qasim0787

回答

1

这会工作,但你必须将所有数据转换为相同的格式:

with test_data(ID1, NAME1, PRICE, DATE1) 
as (
select 123, 'JOHN', 22,  '1/1/2010' from dual union all 
select 234, 'KING', 50,  '5/10/2009' from dual union all 
select 345, 'JACK', 400, '30/11/210' from dual 
) 

select ID1, DATA 
FROM 
(
    select ID1, DATA, COL, 
    row_number() over (partition by ID1 order by id1) RN, 
    dense_rank() over (order by id1) DR 
    from (
    select 
     cast(ID1 as varchar(10)) ID1, 
     cast(NAME1 as varchar(10)) NAME1, 
     cast(PRICE as varchar(10)) PRICE, 
     cast(DATE1 as varchar(10)) DATE1 
    FROM test_data 
) 
    unpivot 
    (
    DATA for COL in (NAME1, PRICE, DATE1) 
) 
) 
where DR = RN 


ID1  DATA  
---------- ---------- 
123  JOHN  
234  50   
345  30/11/210 
0
select 
    cast(ID as varchar(10)), 
    cast(NAME as varchar(10)) 
from table_A 
where ID = 123 

union all 

select 
    cast(ID as varchar(10)), 
    cast(PRICE as varchar(10)) 
from table_A 
where ID = 234 

union all 

select 
    cast(ID as varchar(10)), 
    cast(DATE as varchar(10)) 
from table_A 
where ID = 345; 
+0

我创建了这个表,例如我只有3个ID和3列,但在现实生活中有100个列和100个ID。它很难创建这么大的代码。 – Qasim0787