I have the following tables
table 1
ID1 YEAR1
1 1980
2 1964
3 1910
table 2
ID2 YEAR2 VALUE
1 2000 A
1 1900 B
2 1950 C
2 1900 B
3 2000 C
3 1970 B
4 1900 D
4 1800 E
I would like to join / query these tables to:
for each ID1 in table 1 match, add a column named VALUE - so the column names would be A, B, ... and so on, and the column would be either TRUE(T) or FALSE(F).
The column A ... would be TRUE, if there was ID1 matching ID2 from table 2, and the YEAR2 for that given row in table 2 which matched ID2 was less than YEAR1 from that table 1 having given 1, and VALUE from row having ID2 from table 2 had A
So the resultant table would be as follows:
ID1 YEAR1 A B C D E
1 1980 F T F F F
2 1964 F T T F F
3 1910 F F F F F
You have marked your question as
postgresql
so I will give a PostgreSQL answer, with common table expressions and a pivot table as provided by the tablefunc extension.This is in fact a typical example of problems best expressed with the help of pivot tables.
As you see, the most tedious part is filling falses where the pivot table has nulls.
You can use a query like the following:
If, e.g. value of column
A
is1
, then this is considered asT
, otherwise it is considered as aF
.Demo here
You can use group by as Giorgos or joins like this:
I would simply use conditional aggregation and boolean types: