SQL按最近的dateselect行

使用以下查询和结果,我正在查找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 

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

 SELECT CHARGEID, CHARGETYPE, MAX(SERVICEMONTH) AS "MostRecentServiceMonth" FROM INVOICE GROUP BY CHARGEID, CHARGETYPE 

所以这不是请求者所要求的,而是“SQLselect最近date的行”的答案。

修改自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 
 SELECT chargeId, chargeType, MAX(serviceMonth) AS serviceMonth FROM invoice GROUP BY chargeId, chargeType 

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

在简单的你可以通过以下方式实现:

 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 
 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有不同的收费types组合。希望这个简单的查询有助于考虑less的performance时间…