首页 > 解决方案 > 如何匹配 SQL 中的数据(覆盖率)

问题描述

我在尝试匹配 SQL 中的数据时遇到问题...我想避免使用游标或循环。

我有一个表 ConfigurationItems :

参考表

+----------+--------+-----+
| ConfigId | ItemId | Qty |
+----------+--------+-----+
|     1    |    A   |  1  |
+----------+--------+-----+
|     1    |    B   |  1  |
+----------+--------+-----+
|     1    |    C   |  1  |
+----------+--------+-----+
|     2    |    E   |  1  |
+----------+--------+-----+
|     2    |    D   |  1  |
+----------+--------+-----+

我有一个临时表来存储我需要计算的数据:

临时表

+--------+-----+
| ItemId | Qty |
+--------+-----+
| B      | 1   |
+--------+-----+
| C      | 1   |
+--------+-----+
| D      | 1   |
+--------+-----+

我需要找到每个配置的匹配比率(configId),键首先是ItemId,然后我应该弄清楚如何将Qty变量整合到比率中。

预期结果 :

结果

+----------+--------------------------------------------+
| ConfigId | Match %                                    |
+----------+--------------------------------------------+
| 1        | (nb matched ) / (tot compared) = 2/6 = 33% |
+----------+--------------------------------------------+
| 2        | 1/5 = 20%                                  |
+----------+--------------------------------------------+

编辑:我删除了 qty 部分,因为它看起来很混乱

到目前为止我所尝试的:

do
Begin
create local temporary column table #reference (configId int, ItemId varchar(32), Qty int);
INSERT INTO #reference values(1, 'A',1);
INSERT INTO #reference values(1,'B',2);
INSERT INTO #reference values(1,'C',1);
INSERT INTO #reference values(2,'E',1);
INSERT INTO #reference values(2,'D',1);
INSERT INTO #reference values(3,'B',1);

create local temporary column table #tempTable (ItemId varchar(32), Qty int);
INSERT INTO #tempTable values('B',1);
INSERT INTO #tempTable values('C',2);
INSERT INTO #tempTable values('D',1);

SELECT ref.configID, Count(temp.ItemId),Count(ref.ItemId),  SUM(ABS(ref.qty - IFNULL(temp.qty,ref.qty))) as QtyDiff
FROM #reference as ref 
LEFT JOIN #tempTable as temp on temp.ItemId = ref.ItemId
GROUP BY ref.configID;
End;

标签: sqlhana

解决方案


我觉得你的逻辑有点难以理解。你基本上想要条件聚合。我认为这是您想要的两个关键数字:

select r.configid,
       sum(r.qty) as total_qty
       sum(case when t.qty <= r.qty then t.qty else r.qty end) as num_matched_qty
from reference r left join
     temptable t
     on r.itemid = t.itemid 
group by r.configid

推荐阅读