2016-06-23 3 views
-1

내가 3 열이있는 테이블이) 및 날짜 스탬프. 나는 두 typeshift 사이에 사용 된 시간을 계산하려면 - 잔유 특정에 즉, 1, 17빼기 유형과 워크 플로우 테이블에 날짜와 datestamps는

나는이 같은 SQL 플러스 구문을 시도하고 또한 별칭을 사용하는 것을 시도했다 : 어떤 제안?

select resid, date - date 
from tablename 
where resid, date in 
(select resid, date from tablename 
where type='1') 
and 
where resid, date in 
(select resid, date from tablename 
where type='17') 
and tablename.resid=tablename.resid 
+2

는 오직 하나의 각'resid'에 대한 제 1 형 및 17의 각있을 것이다; 거기에는 언제나 하나씩있을 것입니까? 그렇지 않다면 (유형 1은 존재하지만 17은 (아직), 또는 2 가지 17이 있음) 무엇이 표시되어야합니까? 샘플 데이터와 예상 출력이 도움이 될 것입니다. –

+1

무엇이 문제입니까? 샘플 데이터 또는 오류 메시지를 보여주십시오. – kevinsky

답변

1
SELECT a.resid, a."type" type1, a."date" date1, b."type" type17, b."date" date17, b."date" - a."date" AS date_diff 
    FROM tablename a JOIN tablename b ON a.resid = b.resid AND b."type" = '17' 
WHERE a."type" = '1' AND a.resid = :resid 

열 이름으로 오라클 예약어를 사용하지 마십시오.

SELECT :resid resid, 
     (select "date" FROM tablename WHERE resid = :resid AND "type" = '17') - 
     (select "date" FROM tablename WHERE resid = :resid AND "type" = '1') date_diff 
    FROM DUAL 
1

귀하의 시도 쿼리가 in 전에 열 목록을 괄호없는 - 그래서 where (resid, date in)해야한다 - 또한 유효하지 않은 and where을 가지고 있으며, (잔유, 유형) 고유 때 당신이 할 수있는 아마 다른 문제. 대부분 두 개 모두 같은 행 (유형 1)에서 나오기 때문에 값을 뺀 값이 항상 0이되기 때문에 원하는 것을하지 않습니다. 당신은 조건부 집계 사용할 수

다음 case가 null 또는 일치하는 각 행에 대한 날짜 스탬프 중 하나를 제공

select resid, 
    min(case when type_id = 17 then date_stamp end) 
    - min(case when type_id = 1 then date_stamp end) as diff 
from tablename 
where type_id in (1, 17) -- optional 
and resid = :some_value 
group by resid; 

을; 그런 다음 집계를 통해 (null이 아닌 것을 선호하는) 단일 값을 얻을 수 있습니다.

유형 ID 중 하나만 존재하면 차이는 널입니다.

배수가있을 수있는 경우 min()을 17에서 max()으로 변경하고 싶을 수 있습니다. 실제로 필요한 것이 달려 있습니다.

빠른 데모 :

with tablename(resid, type_id, date_stamp) as (
    select 1, 1, sysdate - 10 from dual 
    union all select 1, 17, sysdate - 7 from dual 
    union all select 2, 1, sysdate - 5 from dual 
    union all select 2, 17, sysdate - 3 from dual 
    union all select 3, 1, sysdate - 10 from dual 
) 
select resid, 
    min(case when type_id = 17 then date_stamp end) 
    - min(case when type_id = 1 then date_stamp end) as diff 
from tablename 
where type_id in (1, 17) -- optional 
--and resid = 2 
group by resid; 

    RESID  DIFF 
---------- ---------- 
     1   3 
     2   2 
     3