so here is the deal, and all google search i could find has different scenarios, but nothing matching my situation :-).
this will be coded in VB.net, but since its sql syntax i can easily build it into vb later.
so i have a table from which i will grab a row with numbers: select n1, n2, n3, n4, n5 from TempTable
essentially this will come back with something like the 3, 8, 12, 5, 33
i now have a 2nd table with the same columns (n1...n5)
i need to find which rows in the 2nd table which have more or equal than 2 numbers matching from the 1st set of numbers (3 or 8 or 12 or 5 or 33).
so if the 2nd table would look like this:
4, 3, 57, 33, 1
5, 6, 87, 21, 44
65, 3, 12, 7, 8
then the query should return 2 (1st and last row)
i hope that makes sense :-)
Thank you for your help!
I would first normalize the 2 tables, so that there is only an ID and the value (and maybe the position if that may be relevant). Let's call them A2 and 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
Then get only the records 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
And finally count them:
SELECT COUNT(*) FROM ...
In a single query that could look like this (but I recommend you make views for A2 and 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.