查找与特定项目至少有 n 个值的所有行

Find all rows, that have at least n values in common with a specific item

我有一个 table,有点像这样:

Items
-----------
    ID Value1 Value2 Value3 Value4 Value5 Value6
    1  345895 435234 342534 678767 5455   423555
    2  3245   549238 230944 923948 234488 234997
    3  490458 49349  234234 87810  903481 3940102
    4  849545 435234 67678  98741  99084  978897

我将如何编写一个查询,找到所有项目,这些项目至少有 3 个值(只是一个例子,可能超过 3 个)与特定项目相同,即我有一个项目

    345895 435234 67678 98741 5455 423555

和运行这个查询会给我

 1  345895 435234 342534 678767 5455   423555
 4  849545 435234 67678  98741  99084  978897

如有任何帮助,我们将不胜感激。谢谢。

这是一种方式:

; with sub as(
select 345895 as mynum
union all select 435234
union all select 67678
union all select 98741
union all select 5455
union all select 423555
)
select i.*
from items i
join
    (
        select x.id
        from(
                select id, value1 as val from items union all
                select id, value2 from items union all
                select id, value3 from items union all
                select id, value4 from items union all
                select id, value5 from items union all
                select id, value6 from items
                ) x join sub s on x.val = s.mynum
        group by x.id
        having count(*) >= 3
    ) x on x.id = i.id

Fiddle: http://sqlfiddle.com/#!6/1dff3/2/0

您可以在 WHERE 子句中使用 CASE 语句来计算匹配数:

SELECT i.*
FROM Items AS i
CROSS JOIN ( VALUES ( 345895, 435234, 67678, 98741, 5455, 423555) ) AS Item(v1, v2, v3, v4, v5, v6)
WHERE (CASE WHEN i.Value1 = Item.v1 THEN 1 ELSE 0 END) +
            (CASE WHEN i.Value2 = Item.v2 THEN 1 ELSE 0 END) +
            (CASE WHEN i.Value3 = Item.v3 THEN 1 ELSE 0 END) +
            (CASE WHEN i.Value4 = Item.v4 THEN 1 ELSE 0 END) +
            (CASE WHEN i.Value5 = Item.v5 THEN 1 ELSE 0 END) +
            (CASE WHEN i.Value6 = Item.v6 THEN 1 ELSE 0 END) >= 3