如何编写一个sql来动态添加Oracle中的一些计算行?

时间:2017-11-19 16:09:28

标签: sql oracle

我有一张这样的表:

id  name    value   
1   elec    10  
1   water   20  
2   elec    15  
2   water   45

现在我需要在select query的结果中动态添加一些行:

id  name    value   
1   elec    10  
1   water   20  
1   ratio   0.5

2   elec    15  
2   water   45  
2   ratio   0.33    

动态添加两行,我该怎么办?

3 个答案:

答案 0 :(得分:2)

使用ELEC,WATER和RATIO列“显示”结果会更有意义 - 每个ID一行。下面的解决方案显示了如何有效地执行此操作(仅读取基表一次)。

with
  inputs ( id, name, value ) as (
    select 1, 'elec' , 10 from dual union all 
    select 1, 'water', 20 from dual union all
    select 2, 'elec' , 15 from dual union all
    select 2, 'water', 45 from dual
  )
-- End of simulated inputs (not part of the solution).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select id, elec, water, round(elec/water, 2) as ratio
from   inputs
pivot  ( min(value) for name in ('elec' as elec, 'water' as water ) )
;

        ID       ELEC      WATER      RATIO
---------- ---------- ---------- ----------
         1         10         20         .5
         2         15         45        .33

如果您需要以原始帖子中显示的格式显示结果,则可以像这样进行忽略(仍然仅读取基表一次):

with
  inputs ( id, name, value ) as (
    select 1, 'elec' , 10 from dual union all 
    select 1, 'water', 20 from dual union all
    select 2, 'elec' , 15 from dual union all
    select 2, 'water', 45 from dual
  )
-- End of simulated inputs (not part of the solution).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select id, name, value
from (
    select id, elec, water, round(elec/water, 2) as ratio
    from   inputs
    pivot  ( min(value) for name in ('elec' as elec, 'water' as water ) )
  )
unpivot ( value for name in (elec as 'elec', water as 'water', ratio as 'ratio') )
;

        ID NAME       VALUE
---------- ----- ----------
         1 elec          10
         1 water         20
         1 ratio         .5
         2 elec          15
         2 water         45
         2 ratio        .33

答案 1 :(得分:0)

这是一种方法:

with t as (
      <your query here>
     )
select id, name, value
from ((select t.*, 1 as ord
       from t
      ) union all
      (select id, 'ratio',
              max(case when name = 'elec' then value end) / max(case when name = 'water' then value end)
              ), 2 as ord
      from t
      group by id
     )
    ) tt
order by id, ord;

答案 2 :(得分:0)

如果你在订购方面略有改变就可以了,试试这个。

SELECT id,name,value FROM yourtable 
UNION ALL
SELECT 
                a.id , 
                'ratio' name,  
                a.value/b.value value 
        FROM
                yourtable a 
        JOIN    yourtable b on a.id = b.id
        WHERE   a.name  = 'elec' 
                and b.name  = 'water'
ORDER BY 
        id ,  
        VALUE DESC;

如果您需要将行添加到表本身,请使用。

INSERT INTO yourtable 
SELECT
        a.id  ,
        'ratio'  name,
        a.value/b.value value
FROM
        yourtable a
JOIN    yourtable b on a.id = b.id
WHERE   a.name     ='elec'
        and b.name ='water';