首页 > 解决方案 > 使用 SQL 将前两行计算为第三行

问题描述

子查询给出以下输出(只有两行):

id | cp  | sp  |
----------------
1  | 200 | 300 |
----------------
2  | 400 | 350 |

从上表中,我怎样才能得到以下输出:
即第一表和第三行的联合=(row1/row2)*100

id | cp  | sp  |
----------------
1  | 200 | 300 |
----------------
2  | 400 | 350 |
----------------
3  | 50  |85.71|

标签: sqlamazon-redshift

解决方案


在 Redshift 中,我认为您需要union all

select id, cp, sp
from t
union all
select max(id) + 1, 
       max(case when id = 1 then cp end) * 100.0 / max(case when id = 2 then cp end),
       max(case when id = 1 then sp end) * 100.0 / max(case when id = 2 then sp end)
from t

推荐阅读