【问题标题】:Oracle SQL join the same tableOracle SQL 连接同一张表
【发布时间】:2015-02-26 14:45:12
【问题描述】:

我有一个包含这些列的表 (MyTable): 观点 警报 load_id 计数警报 ...

我使用这个查询:

select point, decode(alarm,0,'new','rec') NewRec, sum (countAlarms) total_alarms, load_id from MyTable
where 1=1 
--and load_id = (select max(load_id) from MyTable ) -0
group by point, decode(alarm,0,'new','rec'), load_id
order by 1, 2
) 

收到这样的东西:

point1 new 1200 111113
point1 rec 6000 111113
point2 new 1220 111113
point2 rec 3000 111113
point3 new 3220 111113
point3 rec 1000 111113
point1 new 1300 111112
point1 rec 6300 111112
point3 new 1220 111112
point3 rec 1100 111112
point1 new 1300 111111
point1 rec 6300 111111
point2 new 1120 111111
point2 rec 3100 111111
point3 new 1220 111111
point3 rec 1100 111111
....

我需要的是:

point   newRec      point   point   point
---------------------------------------
point1  new         1200    1300    1300
point1  rec         6000    6300    6300
point2  new         1220            1120
point2  rec         3000            3100
point3  new         3220    1220    1220
point3  rec         1000    1100    1100

我尝试过使用完整的外部连接,但它不起作用:(

【问题讨论】:

    标签: oracle join outer-join


    【解决方案1】:

    您似乎想要pivot 您的结果集,而不是加入它本身。假设您使用的是 Oracle 11g 或更高版本,您可以在本地执行此操作:

    select * from (
      select point, decode(alarm,0,'new','rec') NewRec, countAlarms, load_id
      from MyTable
    )
    pivot (
      sum(countAlarms) as alarms
      for (load_id) in (111113 as a, 111112 as b, 111111 as c)
    )
    order by 1, 2;
    

    与上面的输出相匹配的示例数据给出:

    POINT  NEWREC   A_ALARMS   B_ALARMS   C_ALARMS
    ------ ------ ---------- ---------- ----------
    point1 new          1200       1300       1300 
    point1 rec          6000       6300       6300 
    point2 new          1220                  1120 
    point2 rec          3000                  3100 
    point3 new          3220       1220       1220 
    point3 rec          1000       1100       1100 
    

    SQL Fiddle demo.

    你必须知道你所依赖的价值观;不清楚您是否提前知道负载 ID,但原始查询中注释掉的负载 ID 过滤器表明您可能不知道。如果您总是想要三个(或任何固定数量的)最高负载 ID,那么可以通过修改内部查询和数据透视条件来实现,例如带有解析 dense_rank() 伪列:

    select * from (
      select point, decode(alarm,0,'new','rec') NewRec, countAlarms,
        dense_rank() over (partition by null order by load_id desc) as rnk
      from MyTable
    )
    pivot (
      sum(countAlarms) as alarms
      for (rnk) in (1 as a, 2 as b, 3 as c)
    )
    order by 1, 2;
    

    SQL Fiddle.

    【讨论】:

    猜你喜欢
    • 2017-07-17
    • 2016-11-27
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 2021-09-30
    相关资源
    最近更新 更多