你可以做一個單一的表掃描(比較t o使用分析函數使用NOT EXISTS
其中將使用兩個表掃描): SQL Fiddle
的Oracle 11g R2架構設置:
CREATE TABLE table_name (ReferenceNum, DateTime, Type) AS
SELECT '123ab', SYSDATE, 'Request' FROM DUAL UNION ALL
SELECT '123ab', SYSDATE, 'Response' FROM DUAL UNION ALL
SELECT '456cd', SYSDATE, 'Request' FROM DUAL UNION ALL
SELECT '456cd', SYSDATE - 2, 'Response' FROM DUAL UNION ALL
SELECT '789ef', SYSDATE, 'Request' FROM DUAL;
查詢1:
SELECT ReferenceNum
FROM (
SELECT ReferenceNum,
COUNT(CASE WHEN TRUNC(DateTime) = TRUNC(SYSDATE) THEN 1 END)
OVER (PARTITION BY ReferenceNum) AS num_today,
COUNT(CASE WHEN TRUNC(DateTime) <> TRUNC(SYSDATE) THEN 1 END)
OVER (PARTITION BY ReferenceNum) AS num_other_day
FROM table_name t
)
WHERE num_today = 1
AND num_other_day = 0
Results :
| REFERENCENUM |
|--------------|
| 789ef |
來源
2015-12-22 16:36:40
MT0
如果ReferenceNum是連續的,您只需要從表A中選擇max(A.referenceNum),A.datetime,A.Type,其中A.datetime> = sysdate-1 group by A.datetime'。如果記錄太多,性能可能不是最好的。 – Nivas
是的,有太多的記錄..和參考是nvarchar ..我將修改參考NUM的問題 – grayman
我想嘗試這樣的事: 'SELECT * FROM表WHERE 日期時間> = TRUNC(SYSDATE, 'DD') 及其在referencenum(SELECT referencenum FROM表 GROUP (*)= 1)' –