SQL按最近日期选择行

时间:2008-10-09 21:05:02

标签: 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

所需:

    CHARGEID    CHARGETYPE  SERVICEMONTH
1   101     R       8/1/2008
2   161     N       2/1/2008

5 个答案:

答案 0 :(得分:134)

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

的结果集
SELECT
  CHARGEID,
  CHARGETYPE,
  MAX(SERVICEMONTH) AS "MostRecentServiceMonth"
FROM INVOICE
GROUP BY CHARGEID, CHARGETYPE

答案 1 :(得分:49)

因此,这不是请求者要求的内容,但它是“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

答案 2 :(得分:8)

SELECT chargeId, chargeType, MAX(serviceMonth) AS serviceMonth 
FROM invoice
GROUP BY chargeId, chargeType

答案 3 :(得分:2)

我看到大多数开发人员使用内联查询而不会看到它对大量数据的影响。

简单来说,你可以通过以下方式实现这一目标:

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

答案 4 :(得分:-1)

select to.chargeid,t0.po,i.chargetype from invoice i
inner join
(select chargeid,max(servicemonth)po from invoice 
group by chargeid)t0
on i.chargeid=t0.chargeid

如果不同的费用ID具有不同的费用类型组合,则上述查询将起作用。希望这个简单的查询有助于将性能时间考虑在内......