选择最大日期没有我想要的结果

时间:2013-11-07 05:13:07

标签: sql postgresql greatest-n-per-group

SELECT
mat.matid,
MAX (to_date(to_char (matdatetable.matdateupdate,'yyyy-mm-dd'),'yyyy-mm-dd')),
mat.matuserid,
mat.matname,    
mat.matprice    
FROM
matdatetable
LEFT JOIN mat ON matdatetable.sourceid = mat.matid

RESULT

matid   matdate update      matuserid    matname   matprice
-------------------------------------------------------------    
1       2012-01-01 0:0:0:0  0111-1       aaa       100
1       2012-08-01 0:0:0:0  0111-1       aaa       125
1       2013-08-30 0:0:0:0  0111-1       aaa       150
2       2012-01-01 0:0:0:0  0222-1       bbb       130
2       2012-08-21 0:0:0:0  0222-1       bbb       110
2       2013-07-30 0:0:0:0  0222-1       bbb       100
3       2012-01-01 0:0:0:0  0565-1       ccc       100
3       2013-09-30 0:0:0:0  0565-1       ccc       230

但我想。结果

matid     matdate update    matuserid    matname   matprice
------------------------------------------------------------------
1       2013-08-30 0:0:0:0  0111-1       aaa       150
2       2013-07-30 0:0:0:0  0222-1       bbb       100
3       2013-09-30 0:0:0:0  0565-1       ccc       230

1 个答案:

答案 0 :(得分:0)

SELECT DISTINCT ON (1)
       t.sourceid AS matid
      ,t.matdateupdate::date AS matdate_update
      ,m.matuserid
      ,m.matname   
      ,m.matprice
FROM   matdatetable t
LEFT   JOIN mat m ON m.matid = t.sourceid
ORDER  BY 1, t.matdateupdate DESC;

根据matdateupdate为您提供最新(根据sourceid)条目。你的问题并不清楚你想要什么。

使用sourceid而不是matid,因为您有LEFT JOINmatid可能为NULL。或者您对LEFT JOIN的使用不正确......

此相关答案中DISTINCT ON的说明:
Select first row in each GROUP BY group?

t.matdateupdate::datetimestamp(假设缺少信息)投放到date。这似乎是你想要的。如果您确实需要冗余时间00:00,请改用datetrunc('day', t.matdateupdate)