用两个不同的表进行t / sql查询

时间:2019-05-22 17:32:46

标签: sql oracle

enter image description here

我需要创建一个oracle select语句,该语句返回table1中的acct,name,city,splitcost和table2中的APIcost。 table1将90分为3个差异。数量,因为它们分布在其他地方。 table2是API下载,总共只有1条记录,共90条。我需要将结果显示为第二个视图仅显示APIcost总计90。每访问一次。
希望这是有道理的。如果我使用的是sql,那么我很有可能。做一个临时表,但是它必须在Oracle中完成,我也没用过。

1 个答案:

答案 0 :(得分:0)

不需要临时表,只需建立一个等级并对其执行case语句,即可用api_cost填充第一行。我不知道您想要哪一行,因此请使用“ order by”子句让它执行您想要的行。

/* Building out your data to a "temp table" */
with table1 as
(select 1111 as acct, 'john' as name, 'hampton' as city, 30 as split_cost, 90 as 
api_cost from dual union all
select 1111 as acct, 'john' as name, 'hampton' as city, 40 as split_cost, 90 as 
api_cost from dual union all
select 1111 as acct, 'john' as name, 'hampton' as city, 20 as split_cost, 90 as 
api_cost from dual union all
select 1111 as acct, 'john' as name, 'hampton' as city, 20 as split_cost, 90 as 
api_cost from dual)
/* You need nothing above here, just below */
select acct, name, city, split_cost, 
case when rank() over (partition by acct, name, city  order by split_cost, rownum) = 
1 then api_cost
     else null
     end as api_cost
from table1; --substitute your table name here

OUTPUT:
ACCT    NAME    CITY    SPLIT_COST  API_COST
1111    john    hampton 20          90
1111    john    hampton 20  
1111    john    hampton 30  
1111    john    hampton 40