SQL返回组的第一行

时间:2015-10-15 15:07:35

标签: sql postgresql select duplicates

我的要求:

SELECT this, annonceur, campagne, date FROM campagne ORDER BY id ASC

返回:

this    annonceur   campagne    date
A_d20151006174516_rBLA_175030   Bla Bla(001)    2015-10-07 17:51:35.290706
A_d20151006174516_rBLA_175030   Bla Bla(002)    2015-10-07 17:51:35.488242
A_d20151006174516_rBLA_175030   Bla Bla(003)    2015-10-07 17:51:35.530307
A_d20151006174516_rBLA_175030   Bla Bla(004)    2015-10-07 17:51:35.559641

A_d20151008124248_rBLA_124409   Bla Bla(001)    2015-10-09 12:44:13.612378
A_d20151008124248_rBLA_124409   Bla Bla(002)    2015-10-09 12:44:13.708588
A_d20151008124248_rBLA_124409   Bla Bla(003)    2015-10-09 12:44:13.717071
A_d20151008124248_rBLA_124409   Bla Bla(004)    2015-10-09 12:44:13.724947
A_d20151008124248_rBLA_124409   Bla Bla(005)    2015-10-09 12:44:13.731896
A_d20151008124248_rBLA_124409   Bla Bla(006)    2015-10-09 12:44:13.738579

A_d20151011190614_rTest_190714  Test    Test 12102015 - v2(001) 2015-10-12 19:07:30.682369
A_d20151011190614_rTest_190714  Test    Test 12102015 - v2(002) 2015-10-12 19:07:30.744372
A_d20151011190614_rTest_190714  Test    Test 12102015 - v2(003) 2015-10-12 19:07:30.787934

A_d20151013175114_rBLA-VIA-HELLO_175240 Bla via Hello   Bla 14102015(001)   2015-10-14 17:56:23.97971
A_d20151013175114_rBLA-VIA-HELLO_175240 Bla via Hello   Bla 14102015(002)   2015-10-14 17:56:24.183737
A_d20151013175114_rBLA-VIA-HELLO_175240 Bla via Hello   Bla 14102015(003)   2015-10-14 17:56:24.269622
A_d20151013175114_rBLA-VIA-HELLO_175240 Bla via Hello   Bla 14102015(004)   2015-10-14 17:56:24.32696

如何只返回每个“块”的第一行,如:

this    annonceur   campagne    date
A_d20151006174516_rBLA_175030   Bla Bla(001)    2015-10-07 17:51:35.290706
A_d20151008124248_rBLA_124409   Bla Bla(001)    2015-10-09 12:44:13.612378
A_d20151011190614_rTest_190714  Test    Test 12102015 - v2(001) 2015-10-12 19:07:30.682369
A_d20151013175114_rBLA-VIA-HELLO_175240 Bla via Hello   Bla 14102015(001)   2015-10-14 17:56:23.97971

在单个请求中?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

SELECT this, annonceur, campagne, date 
FROM (select *, row_number() over(partition by this order by date) as rn
      from campagne) t
where rn = 1

您可以使用row_number功能。

答案 1 :(得分:1)

在Postgres中,最有效的方法是distinct on。我想你可以做你想做的事情:

SELECT DISTINCT ON (this) this, annonceur, campagne, date
FROM campagne
ORDER BY this, id ASC;