有关连接两个表的查询

时间:2014-08-12 11:42:54

标签: sql oracle

假设我有2张下面的表格

sql> select * from fraud_types ;

fraud_id       fraud_name
--------       ----------
       1       Fraud 1
       2       Fraud 2
       3       Fraud 3
       4       Fraud 4
       5       Fraud 5


sql> select * from alarms ;

fraud_id       dealer      count
--------       ------      -----
       1       Deal 1          5
       3       Deal 1          3
       5       Deal 1          4
       1       Deal 2          2
       2       Deal 2          6
       3       Deal 2          1
       4       Deal 2          7
       5       Deal 2          9

我想加入这两个表并将输出作为

dealer      fraud_id        count
------      --------        -----
Deal 1             1            5
Deal 1             2            0
Deal 1             3            3
Deal 1             4            0
Deal 1             5            4
Deal 2             1            2
Deal 2             2            6
Deal 2             3            1
Deal 2             4            7
Deal 2             5            9

基本上我想要包括fraud_types中的字段,如果报警表中没有,则只在输出中显示0。我怎样才能做到这一点?请帮忙

此致

3 个答案:

答案 0 :(得分:1)

您可以使用cross join来获取所有组合,然后使用left outer join

select d.dealer, f.fraud_id, coalesce(cnt, 0)
from (select distinct dealer from fraud_types) d cross join
     fraud_types f left outer join
     (select dealer, fraud_id, count(*) as cnt
      from fraud_types
      group by dealer, fraud_id
     ) df
     on df.dealer = d.dealer and df.fraud_id = f.fraud_id
order by d.dealer, f.fraud_id;

答案 1 :(得分:1)

分区外连接对于这样的情况非常有用:

select a.dealer, f.fraud_id, nvl(a.count,0) count
  from fraud_types f
  left outer join alarms a
      partition by (a.dealer)
      on a.fraud_id = f.fraud_id
 order by a.dealer, f.fraud_id

对于警报中找到的每个经销商值,这会在警报和fraud_types 之间进行外部联接。

-

如果闹钟表没有(欺诈,经销商)作为键,那么你可以在分区外连接之前进行分组:

select a.dealer, f.fraud_id, nvl(a.count,0) count
  from fraud_types f
  left outer join (
     select fraud_id
          , dealer
          , sum(count) count
       from alarms
      group by fraud_id, dealer
  ) a
      partition by (a.dealer)
      on a.fraud_id = f.fraud_id
 order by a.dealer, f.fraud_id

答案 2 :(得分:0)

   select distinct f.fraud_id,dealer,
   (case when f.fraud_id=t.fraud_id then COUNT else 0 end) counts

   from 
   fraud_types f
   left  join
   alarms t
   partition by (dealer)
   on f.fraud_id=t.fraud_id 
   order by dealer