SQL按最近日期选择行

jgr*_*eep 95 sql oracle

使用以下查询和结果,我正在寻找ChargeId和ChargeType唯一的最新条目.

select chargeId, chargeType, serviceMonth from invoice

    CHARGEID    CHARGETYPE  SERVICEMONTH
1   101     R       8/1/2008
2   161     N       2/1/2008
3   101     R       2/1/2008
4   101     R       3/1/2008
5   101     R       4/1/2008
6   101     R       5/1/2008
7   101     R       6/1/2008
8   101     R       7/1/2008
Run Code Online (Sandbox Code Playgroud)

期望:

    CHARGEID    CHARGETYPE  SERVICEMONTH
1   101     R       8/1/2008
2   161     N       2/1/2008
Run Code Online (Sandbox Code Playgroud)

Mit*_*ers 140

您可以使用GROUP BY按类型和ID对项目进行分组.然后,您可以使用MAX()聚合函数来获取最近的服务月份.下面返回带有ChargeId,ChargeType和MostRecentServiceMonth的结果集

SELECT
  CHARGEID,
  CHARGETYPE,
  MAX(SERVICEMONTH) AS "MostRecentServiceMonth"
FROM INVOICE
GROUP BY CHARGEID, CHARGETYPE
Run Code Online (Sandbox Code Playgroud)

  • 这是完美的.谢谢! (4认同)
  • 你会得到一个额外的行返回.根据他的要求,这是期望的结果. (3认同)
  • 好吧,如果表中有一行101 N 1/1/2008会发生什么? (2认同)
  • 如果我还想用它来拉记录 ID。我该怎么做? (2认同)

tva*_*son 52

所以这不是请求者所要求的,而是"SQL按最近日期选择行"的答案.

修改自http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row

SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( 
    SELECT chargeId,MAX(serviceMonth) AS serviceMonth
    FROM invoice
    GROUP BY chargeId) x 
    JOIN invoice t ON x.chargeId =t.chargeId
    AND x.serviceMonth = t.serviceMonth
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这就是我要找的! (2认同)

Ben*_*ein 9

SELECT chargeId, chargeType, MAX(serviceMonth) AS serviceMonth 
FROM invoice
GROUP BY chargeId, chargeType
Run Code Online (Sandbox Code Playgroud)


小智 8

I see most of the developers use inline query without looking out it's impact on huge data.

in simple you can achieve this by:

select a.chargeId, a.chargeType, a.serviceMonth 
from invoice a
left outer join invoice b
on a.chargeId=b.chargeId and a.serviceMonth <b.serviceMonth 
where b.chargeId is null
order by a.serviceMonth desc
Run Code Online (Sandbox Code Playgroud)