我有以下查询,该查询为单个ID生成多个记录。我试图弄清楚如何将这些多个记录合并为一个记录:
SELECT DISTINCT id, gender, dateofbirth, city, state, zip
FROM t
这可能会给我以下结果集:
1, M, 2000-01-01, dallas, tx, 12345
1, M, 2000-01-01, NULL, NULL, NULL
我想要的是一条记录:
1, M, 2000-01-01, dallas, tx, 12345
当第二行具有不同的数据时,会发生类似的情况:
1, M, 2000-01-01, dallas, tx, 12345
1, M, 2000-01-01, houston, tx, 67890
在这种情况下,我只想选择一条记录,而忽略另一条记录,以便每个id仅包含一条记录。
有没有办法在PostgreSQL中做到这一点?我尝试合并无济于事,想知道是否有某种方法可以解决此问题。
Select * from
(select a.*, row_number () over (partition by id order by city desc)rn
From tablename a
) b where rn=1
上面的查询将始终返回一条记录作为ID。如果有多个city值,一个具有值,一个具有null,则查询将获得具有city值的记录。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句