您能否根据要求建议如何显示以下数据。
表(XX)数据:
id type amount
--- ---- -----
1 A 23.0
2 A 12.0
3 A 34.0
4 B 17.0
5 B 16.0
6 B 20.0
要求:我想显示如下输出
type A amount type B amount
------------- -------------
23.0 17.0
12.0 16.0
34.0 20.0
我尝试了以下查询,但它正在获取重复的行
select a.amount,b.amount
from xx,(select * from xx where type='A')a,(select * from xx where type='B')b
where xx.id=a.id and xx.id=b.id
答案 0 :(得分:2)
这是一种痛苦。您似乎希望将值作为“列表”放在每列中。这不是SQL方式,但它有可能:
select max(a.value) as a, max(b.value) as b
from (select xx.*, rownum as seqnum
from xx
where type = 'A'
) a full outer join
(select xx.*, rownum as seqnum
from xx
where type = 'B'
) b
on a.seqnum = b.seqnum
group by coalesce(a.seqnum, b.seqnum);
如果要保留原始排序,可以将order by id
添加到子查询中。
编辑:
注意,另一种方法是使用union all
:
select max(a) as a, max(b) as b
from ((select rownum as seqnum, value as a, NULL as b from xx where type = 'A'
) union all
(select rownum as seqnum, NULL, value from xx where type = 'B'
)
) ab
group by seqnum;
答案 1 :(得分:1)
如果A的数量始终与B的数量相同,并且A总是第一个:
select ta.amount as "table A amount",
tb.amount as "table B amount"
from tablename ta
join tablename tb on ta.id + (select count(*) from tablename) / 2 = tb.id