它可能类似于之前的问题,但它略有不同(它现在有字段id变量)
我有以下表格。
表1
ID1 YEAR1
1 1980
2 1964
3 1910
和表2
ID2 YEAR2 VALUE FIELD ID
1 2000 A 324
1 1900 B 345
2 1950 C 123
2 1900 B 324
3 2000 C 123
3 1970 B 444
4 1900 D 324
4 1800 E 123
我想加入/查询这些表格:
对于表1中的每个ID1匹配,添加一个名为VALUE的列 - 因此列名称将为A,B,...等等,该列将为TRUE(T)或FALSE(F)。
如果ID1与表2中的ID2匹配,则列A ...将为TRUE,表2中与ID2匹配的给定行的YEAR2小于表1给出id1和VALUE的YEAR1从表2中具有ID2的行得到A并且FIELD ID是324或123
所以结果表如下:
ID1 YEAR1 A B C D E
1 1980 F F F F F
2 1964 F T T F F
3 1910 F F F F F
...
谢谢:)
答案 0 :(得分:0)
SELECT DISTINCT t1.id1,
t1.year1,
CASE WHEN t1.id1 = t2.id2 AND t2.value = 'A' AND t2.year2 <= t1.year1 THEN 'T' ELSE 'F' END AS A,
CASE WHEN t1.id1 = t2.id2 AND t2.value = 'B' AND t2.year2 <= t1.year1 THEN 'T' ELSE 'F' END AS B,
CASE WHEN t1.id1 = t2.id2 AND t2.value = 'C' AND t2.year2 <= t1.year1 THEN 'T' ELSE 'F' END AS C,
CASE WHEN t1.id1 = t2.id2 AND t2.value = 'D' AND t2.year2 <= t1.year1 THEN 'T' ELSE 'F' END AS D,
CASE WHEN t1.id1 = t2.id2 AND t2.value = 'E' AND t2.year2 <= t1.year1 THEN 'T' ELSE 'F' END AS E
FROM table1 t1
INNER JOIN
table2 t2
ON t1.id1 = t2.id2;