在分组依据上查询oracle

时间:2019-02-26 11:01:16

标签: oracle

我有两个16位卡号 [123456789ABCDEF0], [123456ABCDEF7890] 在卡表中。 我在bin表中有两个相似的bin [123456]和[123456789]。我希望查询以计数按bin分组的卡数

1 个答案:

答案 0 :(得分:1)

如果要查找每张卡的最长匹配箱,则可以使用以下方法:

select c.card_number,
  min(b.bin) keep (dense_rank first order by length(b.bin) desc) as bin
from bins b
left join cards c
on c.card_number like b.bin || '%'
group by c.card_number;

,然后进一步汇总这些结果:

select bin, count(card_number)
from (
  select c.card_number,
    min(b.bin) keep (dense_rank first order by length(b.bin) desc) as bin
  from bins b
  left join cards c
  on c.card_number like b.bin || '%'
  group by c.card_number
)
group by bin;

在CTE中有一些示例数据,第一个查询给出:

-- CTEs for sample data
with cards (card_number) as (
            select '123456789ABCDEF0' from dual
  union all select '123456789ABCDEF1' from dual
  union all select '123456ABCDEF7890' from dual
  union all select '123456ABCDEF7891' from dual
  union all select '123456ABCDEF7892' from dual
),
bins (bin) as (
            select '123456' from dual
  union all select '123456789' from dual
  union all select '2345' from dual
)
-- actual query
select c.card_number,
  min(b.bin) keep (dense_rank first order by length(b.bin) desc) as bin
from bins b
left join cards c
on c.card_number like b.bin || '%'
group by c.card_number;

CARD_NUMBER      BIN      
---------------- ---------
123456789ABCDEF0 123456789
123456789ABCDEF1 123456789
123456ABCDEF7890 123456   
123456ABCDEF7891 123456   
123456ABCDEF7892 123456   
                 2345     

第二个给出:

BIN       COUNT(CARD_NUMBER)
--------- ------------------
123456789                  2
2345                       0
123456                     3

我在表之间使用了左外部联接,因此对于没有纸牌的垃圾箱,您得到零计数,但是您可能不希望这样。