2016-01-08 87 views
1

您可以根据需要建议如何显示下面的数据。按照需求显示表格数据的SQL查询

表(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 
+2

你怎么知道'23.0'属于像'17.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; 
+0

你可以使用示例数据运行查询,而不是给出假定的查询 – mohan111

+0

非常感谢Gordon Linoff ..我知道这不是正确的方法,但要求是这样的..不管怎样,非常感谢。 –

+0

我跑了查询,它按照要求工作。 –

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 
+0

如果数据将要更改1列A或B,那么它不会工作 – mohan111

+0

@ mohan111。这就是为什么我说A的数量与B的数量相同的先决条件。 – jarlh