Can I use the results of a calculated field within the same calculated field?

0

I am working on converting some QlikView scripts into Redshift scripts. My QlikView script has a calculated field that uses the calculated result from the previous row to get the result of the current row.

It is checking for a match between the previous ID and current ID. If they don't match, the value is one. If they do match, it's the previous result + 1 as the result.

For example, this is what I'm expecting

IDTimestampOrder
10012023-10-01 08:00:001
10022023-10-01 08:00:001
10022023-10-01 08:30:002
10022023-10-01 09:00:003
10032023-10-01 08:00:001
10032023-10-01 08:15:002
10032023-10-01 08:30:003
10032023-10-01 08:45:004
10042023-10-01 08:30:001

I know that i can use lag() to view the previous ID

CASE WHEN ID != lag(ID,1) over (order by ID, Timestamp) THEN 1 ELSE 0 END as Order

But I am not sure what how to get the previous value of Order within my ELSE statement.

Is it possible to do it this way? Do I need to do it another way?

Any advice or help would be great.

질문됨 7달 전213회 조회
1개 답변
1
수락된 답변

I was able to achieve the results you expected with a different SQL. Kindly see if this will help your use case.

create table tst_ordr
(    ID NUMERIC,
    tmstmp TIMESTAMP
);

INSERT INTO tst_ordr values 
(1001,'2023-10-01 08:00:00'),
(1002,'2023-10-01 08:00:00'),
(1002,'2023-10-01 08:30:00'),
(1002,'2023-10-01 09:00:00'),
(1003,'2023-10-01 08:00:00'),
(1003,'2023-10-01 08:15:00'),
(1003,'2023-10-01 08:30:00'),
(1003,'2023-10-01 08:45:00'),
(1004,'2023-10-01 08:30:00')
;

select *,
    row_number() 
        over (partition by id 
              order by ID, tmstmp)
     as "Order"
from tst_ordr
order by 1,3;

results

profile pictureAWS
답변함 7달 전
  • Thank you!! This is exactly what I was looking for!

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠