oracle中的表中应该存在两条记录,一条来自请求,另一条来自响应。
我想从今天开始选择所有这些记录,但问题是前两天或更长时间内可能存在另一对。 如何确保将返回的记录仅为1,并且在前几天不存在
select A.referenceNum, A.datetime, A.Type from table A where A.datetime >= sysdate - 1
要想象,我想只选择参考号789ef 。
ReferenceNum DateTime类型
123ab(datetoday)请
123ab(datetoday)响应
456cd(datetoday)请
456cd(datetoday-2)响应
789ef(datetoday)请
答案 0 :(得分:1)
您可以使用分析函数在单个表扫描中(与使用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 |
答案 1 :(得分:0)
使用NOT EXISTS
运算符
SELECT A.referenceNum, A.datetime, A.Type
from table A
where A.datetime >= sysdate - 1
AND NOT EXISTS (
SELECT null FROM table B
WHERE A.referenceNum = B.referenceNum
AND b.datetime < a.datetime
)
答案 2 :(得分:0)
SELECT referenceNum
FROM A A1
WHERE TRUNC(A1.datetime) > TRUNC(sysdate)-1
AND A1.Type = 'Request'
AND NOT EXISTS
(SELECT 1
FROM A
WHERE TRUNC(A.datetime) >= TRUNC(sysdate)-1
AND A.Type = 'Response'
AND A.referenceNum = A1.referenceNum
)