D
D
dNertyco2021-10-05 23:48:12
SQL
dNertyco, 2021-10-05 23:48:12

How to make a certain data selection using sql?

You need to select all records that have matches in two or more columns at the same time.
Let's say DB1:

val1 | val2 | val3 | val4
12 | 32 | 66 | 21
35 | 32 | 66 | 88
46 | 32 | 66 | 22
12 | 32 | 67 | 21
12 | 31 | 66 | 21

Let's say DB2:
val1 | val2 | val3 | val4
12 | 32 | 66 | 40
35 | 32 | 66 | 88
46 | 32 | 66 | 40
12 | 32 | 66 | 21
12 | 32 | 66 | 40

I gave two tables as an example, not for sampling, matches are considered only for one table

highlighted in bold, you need to select
the columns for which we are looking for matches are predefined

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dNertyco, 2021-10-06
@dNertyco

Here is the code, by analogy with it everything works

Select *
From  matches AS t1
inner join  matches AS t2 on (t1.id <> t2.id AND t1.P1_20 = t2.P1_20 AND t1.X_04 = t2.X_04)

M
mletov, 2021-10-06
@mletov

SELECT *
FROM
(
SELECT 
         t1.*
        ,t2.*
        (
          (CASE WHEN t1.val1=t2.val1 THEN 1 ELSE 0 END) 
            + (CASE WHEN t1.val2=t2.val2 THEN 1 ELSE 0 END) 
            + (CASE WHEN t1.val3=t2.val3 THEN 1 ELSE 0 END) 
        ) AS checkSum
FROM t1
INNER JOIN t2
ON 1=1
) AS t1
WHERE checkSum >=2

PS Perhaps INNER JOIN ON 1=1 can be replaced with CROSS JOIN if your DB supports it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question