'SQL join concat on inequality
I am struggling with query logic. I have two tables, e.g.
Table1:
| A | B |
|---|---|
| 0 | 1 |
| 0 | 2 |
| 1 | 1 |
| 1 | 2 |
Table2:
| A | B | C |
|---|---|---|
| 0 | 0 | a |
| 0 | 1 | b |
| 0 | 2 | c |
| 1 | 0 | d |
| 1 | 0 | e |
| 1 | 1 | f |
| 1 | 2 | g |
I need to left-join Table2 on Table1 on Table1.A = Table2.A, Table1.B > Table2.B, concatenating the values of C. The result of the above tables would be
| A | B | C |
|---|---|---|
| 0 | 1 | a |
| 0 | 2 | a,b |
| 1 | 1 | d,e |
| 1 | 2 | d,e,f |
How can this be accomplished? (Note the inequality condition on column B.) The actual Table1 has around 10k rows, Table2 10M-ish. I want to use SQL queries on Azure Databricks.
Thanks!
EDIT: OK, never mind. My mistake was to try to do everything in one step. The solution is to join on the equality condition for A, then filter on the inequality condition on B, then concat, e.g.
CREATE TABLE Table1 ( A int, B int);
INSERT INTO Table1 VALUES (0, 1);
INSERT INTO Table1 VALUES (0, 2);
INSERT INTO Table1 VALUES (1, 1);
INSERT INTO Table1 VALUES (1, 2);
CREATE TABLE Table2 (C int, D int, E varchar(2));
INSERT INTO Table2 VALUES (0, 0, 'a');
INSERT INTO Table2 VALUES (0, 1, 'b');
INSERT INTO Table2 VALUES (0, 2, 'c');
INSERT INTO Table2 VALUES (1, 0, 'd');
INSERT INTO Table2 VALUES (1, 0, 'e');
INSERT INTO Table2 VALUES (1, 1, 'f');
INSERT INTO Table2 VALUES (1, 2, 'g');
SELECT Table1.A, Table1.B, GROUP_CONCAT(Table2.E)
FROM Table1
LEFT JOIN Table2 ON Table1.A = Table2.C
WHERE Table1.B > Table2.D
GROUP BY Table1.A, Table1.B
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
