SQL:多列和行比较并找到完全匹配

时间:2014-11-17 20:15:04

标签: sql

我有一个场景,我需要找到一个匹配该前缀下所有行和列的前缀。请参阅以下示例,了解比较的工作原理。

我的期望是找到一个匹配的前缀(但不是同名的前缀),它匹配第二个表中的所有行和列。

编写查询以实现此目的的最佳方法是什么。

TABLE1:

accm_pfx     accum_no     accm_value
--------     --------     ----------
AA00         1            A
AA00         3            B
BB00         2            A

TABLE2:

accm_pfx     accum_no     accm_value
--------     --------     ----------
CC00         1            A
CC00         3            B
EE00         1            A
EE00         2            B
EE00         3            C
DD00         9            B

预期结果:

table1.accm_pfx   matching_accm_pfx     table1.accum_no     table1.accm_value
--------          ---------------       ----------          ----------
AA00              CC00                  1                   A
AA00              CC00                  3                   B

2 个答案:

答案 0 :(得分:0)

我可能会想念您正在寻找的内容,但听起来您想加入accum_no和accm_value上的两个表?

SELECT 
    t1.accm_pfx, t2.accm_pfx, t1.accum_no, t1.accm_value
FROM 
    table1 t1
INNER JOIN
    table2 t2 
ON 
    t1.accum_no = t2.accum_no and t1.accm_value = t2.accm_value

答案 1 :(得分:0)

关于什么构成比赛的要求并不清楚,但这会让你大部分都在那里(抱歉愚蠢的别名,你得到的是你付出的代价:)

 with results as (

select 

table1.accm_prfx as a,
table2.accm_prfx as b,
table1.accum_no,
table1.accum_value,
count(1) over (partition by table1_a.accm_prfx) / count(1) over (partition by table1.accm_prfx, table1_a.accum_no, table1_a.accum_value) as TotalRowsA,
count(1) over (partition by table1.accm_prfx, table2.accm_prfx) as matches,
count(1) over (partition by table2_a.accm_prfx) / count(1) over (partition by table2.accm_prfx, table2_a.accum_no, table2_a.accum_value) as TotalRowsB




 from table1 inner join table2 on table2.accum_no = table1.accum_no and table1.accum_value = table2.accum_value
 inner join table1 table1_a on table1_a.accm_prfx = table1.accm_prfx
 inner join table2 table2_a on table2_a.accm_prfx = table2.accm_prfx
 )

 select distinct a, b, accum_no, accum_value from results
 where
 totalrowsa = totalRowsB 
 and matches  = power(totalRowsA,3)

步骤1:找到每个前缀的匹配项和表A和B中的总行数。 第2步:匹配的总数应该是行数的完美立方体。 (2匹配table1中的* 2行* table2中的2行。)

相关问题