通过将行转换为列来输出Oracle SQL查询

时间:2018-10-05 20:21:41

标签: sql oracle

我的oracle数据库表'App'带有以下示例行-

ID  NAME    SN
123 TV      032361097
123 CB      G92970256
236 TV      050791069
345 CB      45681089
456 TV  
456 CB  

我想通过将行转置为列来获取以下格式的输出-

ID  NAME_TV SR_TV       NAME_CB SR_CB
123 TV      032361097   CB      G92970256
236 TV      050791069       
345                     CB      45681089
456 TV                  CB  

3 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

CompletionStage<E> someMethodWithEAAsync() {
    final A a = await(doSomething());
    Foo foo = fooDAO.getFoos(a);
    // ...
    CompletableFuture<B> futureB = ...;
    final B b = await(futureB);
    // ...
    CompletableFuture<C> futureC = ...;
    final C c = await(futureC);
    // ...
    Bar bar = barDAO.getBars(foo);
    // ...
    CompletableFuture<D> futureD = ...;
    D d = await(futureD);
    return completedFuture(someResult(d, bar));
    // or alternatively
    return futureD.thenApply(d -> someResult(d, bar));
}

我确实有一个问题:为什么会有select id, 'TV' as name_tv, sum(case when name = 'TV' then sn end) as sn_tv, 'CB' as name_cb, sum(case when name = 'CB' then sn end) as sn_cb from app group by id; name_tv列?它们似乎是多余的。

答案 1 :(得分:1)

如果只有两个有效的name值,可以通过以下查询完成。

WITH
  tv as (select id, name, sn from app where name = 'TV'),
  cb as (select id, name, sn from app where name = 'CB')
SELECT 
  nvl(tv.id, cb.id) AS id,
  tv.name           AS name_tv,
  tv.sn             AS sn_tv,
  cb.name           AS name_cb,
  cb.sn             AS sn_cb
FROM tv
  FULL OUTER JOIN cb
    ON tv.id = cb.id;

要获取更多值,请使用更棘手的PIVOT:

SELECT * FROM (
  SELECT id, name, sn
  FROM app
) PIVOT (
  MAX(name) as name, MAX(sn) as sn
  FOR name IN ('TV' as TV, 'CB' as CB) --put other name values there
)

答案 2 :(得分:0)

您可以自己加入表格。

select tv.id,
        tv.name as name_tv, 
        tv.sn as sr_tv, 
        cb.name as name_cb,
        cb.sn as sr_cb   
from app tv
join app cb
on tv.id = cb.id
where tv.name = 'TV'
and cb.name = 'CB'