【问题标题】:t/sql query with two different tables具有两个不同表的 t/sql 查询
【发布时间】:2019-05-22 17:32:46
【问题描述】:

我需要创建一个 oracle select 语句,该语句从 table1 返回 acct、name、city、splitcost,从 table2 返回 APIcost。 table1 将 90 拆分为 3 个差异。数量,因为它们分布在其他地方。 table2 是总共 90 条记录中只有 1 条记录的 API 下载。如果我使用内部连接,则通过 acct 链接的每行重复 90 次。我需要结果看起来像第二个视图只显示 APIcost 总计 90。每个帐户一次。
希望这是有道理的。如果我使用的是 sql 我很可能。做一个临时表,但它必须在我没有使用过的 Oracle 中完成。

【问题讨论】:

  • 这种事情真的应该在显示层处理,因为它会导致可怕的SQL。但是如果你确定需要在 SQL 中进行,那么判断哪个table1 记录有apicost 的标准是什么?
  • 匹配帐户的第一次出现。 1111. 我想做代码,但他们想要来自 oracle 的所有数据调用。我不担心页脚总数。我是从我的网格中得到的。
  • 但是你怎么知道哪个出现是“第一次出现”?是否有其他列决定顺序?
  • 没有其他列可以键入。只要 apicost 每个账户只显示一次。在 SQL 中,我可能会加载临时表中的所有行而不是循环。并调用 table2 apicost。添加一个参数。为每个帐户打开标志位。

标签: sql oracle


【解决方案1】:

不需要临时表,只需建立一个排名并在其上执行 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  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2013-12-23
    相关资源
    最近更新 更多