This question is an extension to this post
I want to join four different tables with SQLite which have just two columns in common. However, assume that there are 30+ columns, i.e more than just columns a - h. Please take a look at following example
Table1:
a b lon lat
---------------
22 33 11 22
Table2:
c d lon lat
---------------
1 2 44 45
Table3
e f lon lat
-----------------------
NULL NULL 100 101
Table4
g h lon lat
-----------------------
NULL NULL 200 201
The current solution is the following
SELECT a,b,NULL AS c, NULL AS d,NULL AS e, NULL AS f, NULL AS g, NULL AS h,
lon,lat
FROM table1
UNION ALL
SELECT NULL, NULL,c,d,NULL AS e, NULL AS f, NULL AS g, NULL AS h, lon,lat
FROM table2
UNION ALL
SELECT NULL, NULL,NULL,NULL,e,f, NULL AS g, NULL AS h, lon,lat
FROM table3
UNION ALL
SELECT NULL, NULL,NULL,NULL,NULL,NULL,g,h, lon,lat
from table4
Result:
+------+------+------+------+------+------+------+------+-----+-----+
| a | b | c | d | e | f | g | h | lon | lat |
+------+------+------+------+------+------+------+------+-----+-----+
| 22 | 33 | NULL | NULL | NULL | NULL | NULL | NULL | 11 | 22 |
| NULL | NULL | 1 | 2 | NULL | NULL | NULL | NULL | 44 | 45 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 100 | 101 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 200 | 201 |
+------+------+------+------+------+------+------+------+-----+-----+
- Problem: What if I have not just the columns a until h, but a until z, i.e many many columns in table1, table2, table3, and table4 -> It would be very time-consuming and the structure wouldn't be clear if I had to write everywhere NULL as [letter] in my sql statement
- @zarruq was a huge help and he suggested that In that case I can just use `UNION ALL` and then `PIVOT` to convert columns to rows
- However, I am not sure how to do that. And, I do not know 100% what he means by that.
- EDIT: SQLite does not support pivot: Any other suggestions?