开发者

sql selectL rows to colums without subquery

I have a table in Oracle 10g that contains some information as follows:

SQL> select * from t_test;

      INFO     CODIGO GRUPO
---------- ---------- ----------
       101        190 VTOS
       100        130 VTOS
       102        140 VTOS

I'd like to extract all the rows that have GRUPO='VTOS' and transpose those rows to columns. The values in CODIGO are predetermined(I know which values can be stored in that column), so would like to get something like this:

INFO_190 INFO_130 INFO_140
-------- -------- --------
     101      100      102

I know I can do it with some subqueries, for example:

SELECT (SELECT info
          FROM t_test
         WHERE codigo = 190 AND grupo = 'VTOS') info_190,
       (开发者_JS百科SELECT info
          FROM t_test
         WHERE codigo = 130 AND grupo = 'VTOS') info_130,
       (SELECT info
          FROM t_test
         WHERE codigo = 140 AND grupo = 'VTOS') info_140
  FROM DUAL

but I'd like to find a more efficient way. Can anyone suggest how to do it?


Assuming you have a relatively small number of codigo values, something like the following should work:

select max(decode(codigo, 190, info, '')) info_190,
 max(decode(codigo, 130, info, '')) info_130,
 max(decode(codigo, 140, info, '')) info_140
from t_test
where grupo = 'VTOS';

If you have multiple grupo values, group by grupo and include it in your select clause.


try this..

select case CODIGO when 190 then INFO end AS INFO_190,
case CODIGO when 130 then INFO end AS INFO_130,
case CODIGO when 140 then INFO end AS INFO_140
from t_test where grupo = 'VTOS'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜