tags:

views:

7995

answers:

3

Using the following query and results, I'm looking for the most recent entry where the ChargeId and ChargeType are unique.

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

Desired:

    CHARGEID CHARGETYPE SERVICEMONTH
1   101  R  8/1/2008
2   161  N  2/1/2008
+15  A: 

You can use a GROUP BY to group items by type and id. Then you can use the MAX() Aggregate function to get the most recent service month. The below returns a result set with ChargeId, ChargeType, and MostRecentServiceMonth

SELECT
  CHARGEID,
  CHARGETYPE,
  MAX(SERVICEMONTH) AS "MostRecentServiceMonth"
FROM INVOICE
GROUP BY CHARGEID, CHARGETYPE
Mitchel Sellers
It's Perfect. Thank you!
jgreep
Don't forget to alias the MAX(serviceMonth) field in case you need it downstream.
Ben Hoffstein
ok, so what happens if there is a row101 N 1/1/2008in the table?
tvanfosson
you would get an extra row returned. Which is the desired result based on his requirements.
Carlton Jenke
Added alias to the query in post. tvanfosson - that would be a conditional that added to the result set, which is correct.
Mitchel Sellers
Sorry. I need to read more carefully. I was thinking row that matched max date for a given charge id.
tvanfosson
You might want to change the title. It's misleading.
tvanfosson
If I wanted to also pull the record id with it. How would I do that?
Donny V.
+1  A: 
SELECT chargeId, chargeType, MAX(serviceMonth) AS serviceMonth 
FROM invoice
GROUP BY chargeId, chargeType
Ben Hoffstein
+4  A: 

So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".

Modified from 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 id) x 
    JOIN invoice t ON x.chargeId =t.chargeId
    AND x.serviceMonth = t.serviceMonth
tvanfosson