Postgresql-仅当
我正在寻找一种方法来连接Id上的两列。 Table2 id有重复的id。我需要过滤id,其中test有一个最小值和关联的test2,但删除其余的。 当我使用内部连接和左连接时,我在测试中得到了多个IDPostgresql-仅当,postgresql,Postgresql,我正在寻找一种方法来连接Id上的两列。 Table2 id有重复的id。我需要过滤id,其中test有一个最小值和关联的test2,但删除其余的。 当我使用内部连接和左连接时,我在测试中得到了多个ID Sample data Table1 +----+--------+-----+ | Id | weight | seq | +----+--------+-----+ | 58 | 180 | 34 | +
Sample data
Table1
+----+--------+-----+
| Id | weight | seq |
+----+--------+-----+
| 58 | 180 | 34 |
+----+--------+-----+
| 36 | 139 | 33 |
+----+--------+-----+
| 53 | 150 | 91 |
+----+--------+-----+
Table2
+----+------+-------+
| Id | test | test2 |
+----+------+-------+
| 58 | 90 | 12 |
+----+------+-------+
| 36 | 45 | 19 |
+----+------+-------+
| 36 | 23 | 24 |
+----+------+-------+
| 53 | 20 | 22 |
+----+------+-------+
期望输出
+----+--------+-----+------+-------+
| Id | weight | seq | test | test2 |
+----+--------+-----+------+-------+
| 58 | 180 | 34 | 90 | 12 |
+----+--------+-----+------+-------+
| 36 | 139 | 33 | 23 | 24 |
+----+--------+-----+------+-------+
| 53 | 150 | 91 | 20 | 22 |
+----+--------+-----+------+-------+
SELECT
table1.id,
table1.weight,
table1.seq,
table2.id,
table2.test,
table2.test2
FROM
public.table1
LEFT JOIN public.table2
ON table1.id = table2.id;
SELECT
table1.id,
table1.weight,
table1.seq,
table2.id,
table2.test,
table2.test2
FROM
public.table1
INNER JOIN public.table2
ON table1.id = table2.id;
我的输出
+-----------------------------+
| ID Weight seq id test test2 |
+-----------------------------+
| 36 139 33 36 45 19 |
| 36 139 33 36 23 24 |
| 53 150 91 53 20 23 |
| 58 180 34 58 90 12 |
+-----------------------------+
您可以使用
row\u number()
窗口函数获取具有最小test
值的行:
SELECT t1.*
FROM table1 t1
JOIN (SELECT id, test, test2, RANK() OVER (PARTITION BY id ORDER BY test ASC) rk
FROM table2) t2 ON t1.id = t2.id AND rk = 1
请张贴已尝试到现在请更新在您的question@Kul你可以用你的问题来添加更多的信息——这比一系列评论更容易阅读