I have table1 as following;
a | b | c | d | e | status |
---|---|---|---|---|---|
2 | 7 | 21 | 36 | 43 |
And table2 as following;
a | b | c | d | e |
---|---|---|---|---|
16 | 21 | 22 | 23 | 40 |
5 | 10 | 16 | 27 | 41 |
8 | 10 | 28 | 38 | 39 |
11 | 12 | 13 | 21 | 23 |
7 | 9 | 17 | 19 | 21 |
and would like to update table1.status by finding how many numbers from table1 is matched/available in table2
For instance, based on the above scenarios, the result will be 2 (as mentioned below) because there are only two numbers 7 & 21 in table2;
a | b | c | d | e | status |
---|---|---|---|---|---|
2 | 7 | 21 | 36 | 43 | 2 |
Am using the below mentioned query and is working as expected but wanted any alternative shorter query
UPDATE table1 as t1 SET status = (
CASE WHEN (SELECT SUM(CASE WHEN t1.a IN(t2.a, t2.b, t2.c, t2.d, t2.e) THEN 1 ELSE 0 END) FROM table2 AS t2)>0 THEN 1 ELSE 0 END+
CASE WHEN (SELECT SUM(CASE WHEN t1.b IN(t2.a, t2.b, t2.c, t2.d, t2.e) THEN 1 ELSE 0 END) FROM table2 AS t2)>0 THEN 1 ELSE 0 END+
CASE WHEN (SELECT SUM(CASE WHEN t1.c IN(t2.a, t2.b, t2.c, t2.d, t2.e) THEN 1 ELSE 0 END) FROM table2 AS t2)>0 THEN 1 ELSE 0 END+
CASE WHEN (SELECT SUM(CASE WHEN t1.d IN(t2.a, t2.b, t2.c, t2.d, t2.e) THEN 1 ELSE 0 END) FROM table2 AS t2)>0 THEN 1 ELSE 0 END+
CASE WHEN (SELECT SUM(CASE WHEN t1.e IN(t2.a, t2.b, t2.c, t2.d, t2.e) THEN 1 ELSE 0 END) FROM table2 AS t2)>0 THEN 1 ELSE 0 END )
2
Answers
As commented above, this data model and query request makes no sense.
Use
jsonb
to pivot columns to rows:db<>fiddle here
Agree with previous posters: this this is a terrible data model. But you can get what you are asking for by expanding the columns from table2 into individual rows then determining the distinct values contain as column value in table 1. Finally, count the results. (see demo)