sql - 如何匹配 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;
解决方案
我觉得你的逻辑有点难以理解。你基本上想要条件聚合。我认为这是您想要的两个关键数字:
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
推荐阅读
- python - 如何用 ProcessPoolExecutor 优雅地终止 loop.run_in_executor?
- windows - 如何解决在 Windows 10 上链接 pdfium
- rpm - 如何在 rpm 规范文件中安装符号链接
- android - camera2 api 在 android 8.1.0 上崩溃
- java - 将任何 ISO-8601 格式转换为 Android 中的可读格式
- sql - JSON_Query 与 For Json 路径
- python - 扩展()不产生列表
- sql - 使用 HUE/IMPALA 计数不同
- c# - 插入到 localdb 时重音字符的问题
- python - 为什么 `total_num_virtual_procs` 不等于 MPI 进程的数量?