我有一张桌子,让我们说“记录”结构:
id date
-- ----
1 2012-08-30
2 2012-08-29
3 2012-07-25
我需要在PostgreSQL中编写一个SQL查询来获取每个月的MIN日期的record_id。
month record_id
----- ---------
8 2
7 3
我们看到2012-08-29< 2012-08-30,这是8个月,所以我们应该显示record_id = 2
我尝试过这样的事情,
SELECT
EXTRACT(MONTH FROM date) as month,
record_id,
MIN(date)
FROM Records
GROUP BY 1,2
但它显示了3条记录。
有人可以帮忙吗?
答案 0 :(得分:3)
SELECT DISTINCT ON (EXTRACT(MONTH FROM date))
id,
date
FROM Records1
ORDER BY EXTRACT(MONTH FROM date),date
SQLFiddle http://sqlfiddle.com/#!12/76ca2/3
UPD:此查询:
1)按月份和日期对记录进行排序
2)每个月挑选第一条记录(由于订购,第一条记录有MIN(date)
)
此处详细信息http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT
答案 1 :(得分:2)
select distinct on (date_trunc('month', date))
date_trunc('month', date) as month,
id,
date
from records
order by 1, 3 desc
答案 2 :(得分:2)
如果您有最小重复日期,则会返回倍数:
Select
minbymonth.Month,
r.record_id
From (
Select
Extract(Month From date) As Month,
Min(date) As Date
From
records
Group By
Extract(Month From date)
) minbymonth
Inner Join
records r
On minbymonth.date = r.date
Order By
1;
或者如果你有CTE
With MinByMonth As (
Select
Extract(Month From date) As Month,
Min(date) As Date
From
records
Group By
Extract(Month From date)
)
Select
m.Month,
r.record_id
From
MinByMonth m
Inner Join
Records r
On m.date = r.date
Order By
1;
答案 3 :(得分:2)
select extract(month from date)
, record_id
, date
from
(
select
record_id
, date
, rank() over (partition by extract(month from date) order by date asc) r
from records
) x
where r=1
order by date
答案 4 :(得分:1)
我认为您需要使用子查询,如下所示:
SELECT
EXTRACT(MONTH FROM r.date) as month,
r.record_id
FROM Records as r
INNER JOIN (
SELECT
EXTRACT(MONTH FROM date) as month,
MIN(date) as mindate
FROM Records
GROUP BY EXTRACT(MONTH FROM date)
) as sub on EXTRACT(MONTH FROM r.date) = sub.month and r.date = sub.mindate