我有一张桌子,有点像这样:
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
非常感谢任何帮助。谢谢。
答案 0 :(得分:2)
您可以在CASE
子句中使用WHERE
语句来计算匹配数:
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
答案 1 :(得分:0)
这是一种方式:
; 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