从结果中选择最大日期行

时间:2010-09-08 13:33:45

标签: sql postgresql pervasive pervasive-sql

使用Pervasive SQL,我有一个结果集:

Tp_No     Name        State    Eff_Date     Actual      Billed   
 1006       ABC        TN      2006-07-01     .1          .5
 1006       ABC        TN      2008-02-15     .27         .6
 1006       ABC        TN      2010-09-01     .37         .7
 1022       Widget     TN      2006-07-01     .1          .5
 1022       Widget     TN      2007-02-22     .27         .6
 1022       Widget     TN      2009-01-01     .37         .7
 1022       Widget     TN      2010-11-11     .38         .71

我想要的是每个客户,公司和状态的行,其中日期为MAX:

Tp_No     Name        State    Eff_Date     Actual      Billed 
 1006       ABC        TN      2010-09-01     .37         .7
 1022       Widget     TN      2010-11-11     .38         .71

原因是原始结果集是查询的结果,而不仅仅是直接来自表格,这使事情变得更加困难。

    select a.tp_no, c.name, a.state, b.eff_date, a.er_rate as 'Actual', b.er_rate as 'Billed' 
from "PR_TSUTA" as a 
left join CL_SUTA as b on(a.tp_no=b.loc_no)
left join CL_MAST as c on(b.loc_no=c.loc_no) 
where c.yn_17 = 'A' and a.er_rate != b.er_rate 
order by a.tp_no

提前致谢

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT
    a.tp_no AS ClientNum,
    c.name AS Company,
    a.state AS State,
    MAX(b.eff_date) AS Date
FROM "PR_TSUTA" AS a 
LEFT JOIN CL_SUTA AS b ON a.tp_no = b.loc_no
LEFT JOIN CL_MAST AS c ON b.loc_no = c.loc_no
WHERE c.yn_17 = 'A' AND a.er_rate != b.er_rate 
GROUP BY a.tp_no, c.name, a.state

如果您还需要“实际”和“已结算”值,则应使用greatest-n-per-group查询。