用另一个查询扩充sql查询的输出

时间:2014-03-17 12:35:11

标签: sql oracle variables

我有两个表,我想用第一个表扩充查询的输出 第二个表上另一个查询的值。

我可以使用下面的第二个查询从第二个表中获取我想要的值。 此查询可以返回多行。

select ip_country from table2
where 
account_id = 'customer1' and
created_on >= to_timestamp('15-NOV-2013','dd-MON-yyyy')
order by created_on desc;

输出:

us (null) us (null)

我只对最新的行感兴趣,所以我使用像这样的查询

select ip_country from (select ip_country from table2 
where 
account_id = 'customer1' and
created_on >= to_timestamp('15-NOV-2013','dd-MON-yyyy')
order by created_on desc) where rownum = 1;

输出: us

我想要将其扩充到的查询是:

select
txnid, account_id, result
from table1     
where  
table1.txnid = 101

输出: 101, customer1, PASS

我想写一个像

这样的查询
select
txnid, account_id, result, ip_country = (select ip_country from (select ip_country from table2 
where 
account_id = 'customer1' and
created_on >= to_timestamp('15-NOV-2013','dd-MON-yyyy')
order by created_on desc) where rownum = 1;)
from table1, table2     
where  
table1.txnid = 101;

这当然在语法上是错误的,但希望这传达了意义。 我的问题是如何编写此查询。

期望的输出: 101, customer1, PASS, us

我尝试使用连接而没有任何运气。我省略了一些与查询无关的其他列。我正在研究Oracle DB。请随意将标题更改为更合适的标题,我不太清楚如何更好地表达它。

2 个答案:

答案 0 :(得分:2)

我认为这会做你想做的事情:

select txnid, account_id, result,
       (select max(ip_country) keep (dense_rank first order by created_on desc)
        from table2
        where account_id = 'customer1' and
              created_on >= to_timestamp('15-NOV-2013','dd-MON-yyyy')
       ) as ip_country
from table1 
where table1.txnid = 101;

但是,我认为您的查询有两个简单的问题。首先,子查询中有分号,第二个外部查询中有不必要的连接。上面使用Oracles keep / first功能消除了一层子查询。

答案 1 :(得分:1)

如果需要相同的account_id:

select t1.txnid, t1.account_id, t1.result, t2max.ip_country
from table1 t1, 
(select t2.ip_country, t2.account_id from table2 t2
 where t2.account_id = 'customer1' and 
 t2.created_on >= to_timestamp('15-NOV-2013','dd-MON-yyyy')
 order by t2.created_on desc limit 1) t2max 
where t2max.account_id = t1.account_id
group by t1.txnid, t1.account_id, t1.result;

或者它与table1和table2中的account_id不同:

select t1.txnid, t1.account_id, t1.result, t2max.ip_country
from table1 t1, 
(select t2.ip_country from table2 t2
 where t2.account_id = 'customer1' and 
 t2.created_on >= to_timestamp('15-NOV-2013','dd-MON-yyyy')
 order by t2.created_on desc limit 1) t2max 
group by t1.txnid, t1.account_id, t1.result;