1

我有一张桌子,让我们说“记录”的结构:

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 条记录。

有人可以帮忙吗?

4

5 回答 5

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

于 2012-11-22T19:58:36.980 回答
2

SQL小提琴

select distinct on (date_trunc('month', date))
    date_trunc('month', date) as month,
    id,
    date
from records
order by 1, 3 desc
于 2012-11-22T19:58:11.613 回答
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;

http://sqlfiddle.com/#!1/2a054/3

于 2012-11-22T19:58:19.620 回答
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
于 2012-11-22T20:13:00.643 回答
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
于 2012-11-22T20:02:49.533 回答