views:

61

answers:

2

Hello:

I'd like to know what should be the SQL statement (for ORACLE DBMS) that would get back unique (by CUSTOMER_ID, VEHICLE_ID, DEALER_ID and EVENT_TYPE_ID) rows BUT it will return the latest date (EVENT_INITIATED_DATE) for that row too. I've tried DISTINCT and GROUP BY, but wasn't able to figure out how to handle EVENT_INITIATED_DATE (that is DATE data type).

CUSTOMER_ID            VEHICLE_ID             DEALER_ID  EVENT_TYPE_ID          EVENT_INITIATED_DATE      
---------------------- ---------------------- ---------- ---------------------- ------------------------- 
22197630               23093399               6040       20                     11-JAN-07                 
22197630               23093399               6040       5                      11-JAN-07                 
22197630               23093399               6040       4                      11-JAN-07                 
22197630               23093399               6040       3                      11-JAN-07                 
22197630               23093399               6040       4                      19-JAN-06                 
+6  A: 
select CUSTOMER_ID, VEHICLE_ID, DEALER_ID, EVENT_TYPE_ID, 
    max(EVENT_INITIATED_DATE)
from MyTable 
group by CUSTOMER_ID, VEHICLE_ID, DEALER_ID, EVENT_TYPE_ID
RedFilter
You typed faster then me!
Avitus
This of course assumes the Event_initiated_date is a data type for dates and not string data. This will not work on string dates because the ordering is differnt and thus the wrong max data could be returned. (or at least in SQl Server but I bet it makes a differnce in ORacle as well)
HLGEM
@HLGEM: Good point, my query does assume a date data type.
RedFilter
Seen people struggle to make sometihgn like this work and not realize that a string sort would never at times not pull the right value, it is important to always store dates as dates!
HLGEM
+1  A: 

Distinc won't work.

Group by - and then one of the MAX / MIN etc. functions for the additional fields.

SELECT Customer_ID, VEHICLE_ID, MAX(EVENT_INITIATED_DATE)... ...GROUP BY Customer_ID, VEHICLE_ID

Hope that helps ;)

TomTom