2016-05-12 111 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