2008-10-09 22 views
85

Usando la siguiente consulta y resultados, estoy buscando la entrada más reciente donde ChargeId y ChargeType son únicos.SQL seleccionando filas por fecha más reciente

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 

deseado:

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

Respuesta

121

Usted puede utilizar un grupo POR para agrupar los elementos según el tipo y la identificación. Luego puede usar la función Agregar MAX() para obtener el mes de servicio más reciente. El siguiente devuelve un conjunto de resultados con ChargeId, ChargeType y MostRecentServiceMonth

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

es perfecto. ¡Gracias! – jgreep

+1

No olvide alias el campo MAX (serviceMonth) en caso de que lo necesite en sentido descendente. –

+2

bien, entonces, ¿qué sucede si hay una fila 101 N 1/1/2008 en la tabla? – tvanfosson

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

Así que esto no es lo que el solicitante estaba pidiendo, pero es la respuesta a "filas SQL seleccionar por la fecha más reciente".

Modificado de 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 
+0

¡Gracias! ¡Esto es lo que estaba buscando! – Diana

+0

No parece ser compatible con vistas. – Nuzzolilo

-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 

La consulta anterior funcionará si la distinta Identificación del cargo tiene diferentes combinations.Hope chargetype esta consulta sencilla ayuda con poco tiempo de rendimiento en consideración ...

2

Veo que la mayoría de los desarrolladores usan consultas en línea sin tener en cuenta su impacto en grandes cantidades de datos.

en simples que usted puede lograr esto mediante:

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 
Cuestiones relacionadas