如何为每个不同的名称获取1个地址?

时间:2016-02-25 03:42:33

标签: sql postgresql

我有the following SQL fiddle

Template.CoursePage.helpers({
    Lectures: function() {
        return Lectures.find({courseId: this._id});
    },
    Questions: function(lectureId) {
        return Questions.find({courseId: this._id, lectureId: lectureId});
    }
});

每个名称可以包含多个地址。例如鲍勃可以在纽约和洛杉矶有一个地址。玛丽可以住在巴黎和芝加哥。我想获得不同的名称,然后返回他们的地址,这些地址已经过了1天没有更新(无论哪个地址都没关系......只要它没有更新)。我有:

CREATE TABLE tester(
  name TEXT,
  address TEXT
  updated DATE
 )

我明白了:

SELECT DISTINCT ON(name) name, address FROM tester WHERE updated < (NOW() - interval '1 day') 
  HAVING count(address) > 1;

1 个答案:

答案 0 :(得分:0)

要使用distinct on,您需要order by

SELECT DISTINCT ON (name) name, address
FROM tester
WHERE updated < (NOW() - interval '1 day') 
ORDER BY name;

然而,这并没有获得具有多个地址的那些。为此,请使用GROUP BY

SELECT name, MAX(address)
FROM tester
WHERE updated < (NOW() - interval '1 day') 
GROUP BY name;