从查询结果中选择最新记录

时间:2017-06-28 07:02:27

标签: sql

我有SQL query以下根据系统日期从3个表中获取记录。     表service_request有多条记录,现在我想根据service_request表ID获取最新的行。

给定query,提供12条记录,12条中只有3条SR.ID是唯一的,我想在我的结果中仅获取3条记录。

SELECT SR.ID, BR.SVC_PT_UDC_ID, D.UDC_ID, D.SUB_TYPE, SR.TYPE_CD, SR.SUB_TYPE_CD, BR.REQUEST_STATUS,BR.EXTNL_BILLING_REQUEST_ID,BR.INSERT_TIME
FROM BILLING_REQUEST BR 
JOIN SERVICE_REQUEST SR
ON BR.SVC_PT_ID = SR.SVC_PT_ID
JOIN DEVICE D
ON SR.DEVICE_ID = D.ID
WHERE 
REQUEST_SRC = 'DDSWebServiceImportAdapter' 
AND TRUNC(BR.INSERT_TIME) = TRUNC(SYSDATE) -1
AND (SR.TYPE_CD != 'Meter Service' AND SR.TYPE_CD != 'RMM');

1 个答案:

答案 0 :(得分:0)

Modified question, 

Hi,

I have below query which fetches record from 5 tables based on system date.

BILLING_REQUEST table has 4 records for sysdate-1 and I need all of these to be present
But SERVICE_REQUEST table gives multiple records, total 40, in my final result I need only 4 records which correspond to BILLING_REQUEST table

TABLE STRUCTURE

Billing Request TABLE
ID (PK)       EXTNL_BILLING_REQUEST_ID(STRING)     SVC_PT_UDC_ID(STRING)      SVC_PT_ID(FK)   STATUS    INSERT_TIME(TIMESTAMP)
-- Contains 4 records

SVC_PT TABLE
ID (PK)      UDC_ID(STRING)    INSERT_TIME(TIMESTAMP)
-- Contains 4 records

SVC_PT_DEVICE_REL
ID (PK)     SVC_PT_ID (FK)     DEVICE_ID (FK)    EFF_START_TIME(TIMESTAMP)  
-- Contains 4 records

DEVICE TABLE
ID (PK)     UDC_ID(STRING)    TYPE(STRING)     INSERT_TIME(TIMESTAMP)
-- Contains 4 records


SERVICE_REQUEST TABLE
ID (PK)    TYPE_CD(STRING)    SUB_TYPE_CD (STRING)    SVC_PT_ID(FK)   DEVICE_ID (FK)
-- Contains 40 records (only 4 unique SVC_PT_ID are present in this table, so need to fetch the 4 latest ID which corresponds to 4 unique SVC_PT_ID)

QUERY BEING USED
SELECT SR.ID, BR.SVC_PT_UDC_ID, D.UDC_ID, D.SUB_TYPE, 
SR.TYPE_CD, SR.SUB_TYPE_CD, 
BR.REQUEST_STATUS,BR.EXTNL_BILLING_REQUEST_ID,BR.INSERT_TIME
FROM BILLING_REQUEST BR
JOIN SVC_PT_DEVICE_REL SDR
ON BR.SVC_PT_ID = SDR.SVC_PT_ID
JOIN DEVICE D
ON SDR.DEVICE_ID = D.ID
JOIN SERVICE_REQUEST SR
ON BR.SVC_PT_ID = SR.SVC_PT_ID
WHERE 
REQUEST_SRC = 'DDSWebServiceImportAdapter' 
AND TRUNC(BR.INSERT_TIME) = TRUNC(SYSDATE) -6
AND (SR.TYPE_CD != 'Meter Service' AND SR.TYPE_CD != 'RMM')