我有一张如下表所示的表格:
| ID |人|修改了On |
如果我有以下记录:
{id: 1, person: 'John', Modified On: 2014-06-01 12:00:00},
{id: 2, person 'John', Modified On: 2014-06-02 12:00:00},
{id: 2, person 'Kate', Modified On: 2014-06-02 12:08:00},
{id: 2, person 'Sarah', Modified On: 2014-06-02 12:02:00},
{id: 2, person 'Sarah', Modified On: 2014-06-01 12:00:00}
请注意,同一个人“John”和Sarah在那里两次。 6月1日修改一次,6月2日修改。
我想要的是能够选择每个人中的一个,但只能选择他们最早的日期。所以我的结果应该是:
{id: 1, person: 'John', Modified On: 2014-06-01 12:00:00},
{id: 2, person 'Kate', Modified On: 2014-06-02 12:08:00},
{id: 2, person 'Sarah', Modified On: 2014-06-01 12:00:00}
我应该如何构建我的SQL呢?
答案 0 :(得分:1)
----使用解析函数rank(),使其返回一组值中的值的等级。使用子句可以创建一组临时数据。
WITH TEMP AS
(
SELECT id, person, Modified_On,
rank() OVER (PARTITION BY person ORDER BY Modified_On) AS RK
FROM TABLE1
)
SELECT id, person, Modified_On FROM TEMP WHERE RK=1;
答案 1 :(得分:1)
SELECT *
FROM ( SELECT *,
ROW_NUMBER() OVER(PARTITION BY person
ORDER BY "Modified On") AS RN
FROM YourTable) AS X
WHERE RN = 1
答案 2 :(得分:1)
在PostgreSQL中每组只选择一行的正确方法是DISTINCT ON
子句。虽然在这种情况下技术上很简单MIN()
。
SELECT DISTINCT ON (person) id, person, modified_on,
FROM TABLE1
ORDER BY person, modified_on
答案 3 :(得分:0)
尝试:
select *
from my_table t1
where "Modified On" = (select min("Modified On") from my_table t2 where t1.person = p2.person)
这使用子选择来获取每个人的最小日期。
答案 4 :(得分:0)
SELECT id, person, min(Modified On) FROM some_table
Group by person