postgresql group by column并从每个组中选择最早的日期

时间:2017-04-25 21:30:23

标签: postgresql

我尝试选择一个组,计算出现次数,并返回该组中最早的一个。我正在考虑使用具有直接值的子查询,如:

SELECT COUNT(submitdate), priority, 
 (SELECT submitdate FROM opentickets WHERE priority = priority ORDER BY submitdate ASC LIMIT 1) 
FROM opentickets
 WHERE assignee IS NULL
  GROUP BY priority

但我得到所有优先级组的相同日期。有谁知道它是否可以使用这样的列值?例如,"优先级=优先级"成为"优先级=' P1' "那么' P2',' P3'等等。

期望输出

count  priority   submitdate
  12     P1       "2017-04-03 10:48:14"
 152     P2       "2017-03-23 02:24:07"
 308     P3       "2017-03-03 05:06:43"

2 个答案:

答案 0 :(得分:1)

create table test(priority varchar(10), submitdate timestamp);
insert into test values
('P1', '20170101'),
('P1', '20170102'),
('P1', '20170103'),
('P2', '20170301'),
('P2', '20170501'),
('P3', '20170501'),
('P3', '20170601'),
('P3', '20170705');

select     priority, 
           count(submitdate) as count_dates,
           max(submitdate) as max_date
from       test
group by   priority;
✓

8 rows affected

priority | count_dates | max_date           
:------- | ----------: | :------------------
P2       |           2 | 2017-05-01 00:00:00
P3       |           3 | 2017-07-05 00:00:00
P1       |           3 | 2017-01-03 00:00:00

dbfiddle here

答案 1 :(得分:0)

使用max

SELECT COUNT(submitdate), priority, 
max(submitdate)
FROM opentickets
WHERE assignee IS NULL
GROUP BY priority