开发者

What is the SQL statement that removes duplicates but keep additional column's data?

开发者 https://www.devze.com 2022-12-29 20:52 出处:网络
I\'d like to know what should be the SQL statement (for ORACLE DBMS) that would get back unique (by CUSTOMER_ID, VEHICLE_ID, DEA开发者_如何学CLER_ID and EVENT_TYPE_ID) rows BUT it will return the late

I'd like to know what should be the SQL statement (for ORACLE DBMS) that would get back unique (by CUSTOMER_ID, VEHICLE_ID, DEA开发者_如何学CLER_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                 


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


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 ;)


select CUSTOMER_ID, VEHICLE_ID, DEALER_ID, EVENT_TYPE_ID,
EVENT_INITIATED_DATE
from MyTable a 
group by CUSTOMER_ID, VEHICLE_ID, DEALER_ID, EVENT_TYPE_ID,
EVENT_INITIATED_DATE HAVING EVENT_INITIATED_DATE = 
  ( select MAX(EVENT_INITIATED_DATE) from MyTable WHERE CUSTOMER_ID =
     a.CUSTOMER_ID AND VEHICLE_ID = a.VEHICLE_ID AND DEALER_ID =
     a.DEALER_ID AND a.EVENT_TYPE_ID = EVENT_TYPE_ID );
0

精彩评论

暂无评论...
验证码 换一张
取 消