Postgresql选择min Date值

时间:2015-06-11 23:59:10

标签: sql postgresql postgresql-9.3 dml

这些是我的表格:

表:门票

  • ticketid:serial
  • userid:integer
  • dateticket:date
  • timeticket:time

表:用户

  • userid:serial
  • 用户名:varchar
  • 密码:varchar

这些是我的数据:

    userid  username  password
    1        user1         123
    2        user2         123

ticketid  userid  dateticket timeticket
    1        1    2015-05-27 14:47:14
    2        1    2015-05-27 14:47:15
    3        1    2015-05-27 14:47:16
    4        2    2015-05-27 14:47:17
    5        2    2015-05-27 14:47:18
    6        2    2015-05-12 14:47:19

我想显示分配给具有用户ID的用户的票证金额以及带有时间的最短日期。

我目前的查询是:

select 
    min(t.dateticket) as mydate,
    (select min(ti.timeticket) as mytime from tickets ti where ti.userid=t.userid),
    t.userid,
    count(t.ticketid) as my_all
from
    tickets t
group by 
    t.userid
order by 
    my_all asc, 
    mydate asc, 
    mytime asc;

The current result is:

        mydate     mytime     userid  my_all
      2015-05-27   14:47:14     1        3
      2015-05-12   14:47:17     2        3


The expected result is:

        mydate     mytime     userid  my_all
      2015-05-12   14:47:19     1        3
      2015-05-27   14:47:14     2        3

1 个答案:

答案 0 :(得分:0)

我认为这会做你想做的事情:

select distinct on (userid) dateticket, timeticket, userid,
       count(*) over (partition by userid) as my_all
from tickets t
order by userid, dateticket, timeticket;

distinct on根据order by返回每个组中的第一条记录。诀窍是使用窗口函数获取所有票证的计数。

编辑:

要进行其他排序,请使用子查询:

select t.*
from (select distinct on (userid) dateticket, timeticket, userid,
             count(*) over (partition by userid) as my_all
      from tickets t
      order by userid, dateticket, timeticket
     ) t
order by my_all, dateticket, timeticket.