您好我有下表
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 :(得分: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
答案 1 :(得分: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;