所以这是一笔交易,我能找到的所有Google搜索都具有不同的情况,但与我的情况不符:-)。
这将在VB.net中进行编码,但是由于其sql语法,我以后可以轻松将其构建到vb中。
所以我有一张桌子,我将在桌子上抓一个带数字的行: 从TempTable中选择n1,n2,n3,n4,n5
从本质上讲,它将返回类似3、8、12、5、33
我现在有第二个表,它们具有相同的列(n1 ... n5)
我需要找出第二张表中哪些行与第一组数字(3或8或12或5或33)中匹配的数字大于或等于2。
所以如果第二张表看起来像这样:
4、3、57、33、1
5,6,87,21,44
65、3、12、7、8
然后查询应返回2(第一行和最后一行)
我希望这是有道理的:-)
谢谢您的帮助!
答案 0 :(得分:0)
我首先将2个表标准化,以便只有一个ID和一个值(如果可能的话,可能还有位置)。我们称它们为A2和B2:
SELECT ID, 1 AS Pos, N1 AS Value FROM A
UNION ALL
SELECT ID, 2 AS Pos, N2 AS Value FROM A
UNION ALL
SELECT ID, 3 AS Pos, N3 AS Value FROM A
UNION ALL
SELECT ID, 4 AS Pos, N4 AS Value FROM A
UNION ALL
SELECT ID, 5 AS Pos, N5 AS Value FROM A
然后仅获取具有2个或更多匹配项的记录:
SELECT B2.ID, COUNT(*) AS Matches FROM A2
INNER JOIN B2 ON A2.Value = B2.Value
GROUP BY B2.ID
HAVING COUNT(*) >= 2
最后算一下:
SELECT COUNT(*) FROM ...
在可能看起来像这样的单个查询中(但我建议您为A2和B2创建视图):
WITH A2 AS (
-- Normalize table 1
SELECT ID, 1 AS Pos, N1 AS Value FROM A
UNION ALL
SELECT ID, 2 AS Pos, N2 AS Value FROM A
UNION ALL
SELECT ID, 3 AS Pos, N3 AS Value FROM A
UNION ALL
SELECT ID, 4 AS Pos, N4 AS Value FROM A
UNION ALL
SELECT ID, 5 AS Pos, N5 AS Value FROM A
), B2 AS (
-- Normalize table 2
SELECT ID, 1 AS Pos, N1 AS Value FROM B
UNION ALL
SELECT ID, 2 AS Pos, N2 AS Value FROM B
UNION ALL
SELECT ID, 3 AS Pos, N3 AS Value FROM B
UNION ALL
SELECT ID, 4 AS Pos, N4 AS Value FROM B
UNION ALL
SELECT ID, 5 AS Pos, N5 AS Value FROM B
)
-- Count them
SELECT COUNT(*) FROM (
-- Get only the ones with 2 or more matches
SELECT B2.ID, COUNT(*) AS Matches FROM A2
INNER JOIN B2 ON A2.Value = B2.Value
GROUP BY B2.ID
HAVING COUNT(*) >= 2
) AS T