Could anyone please help to enhance the query below,
select
columns
from
(
select t.*,
sum (case when TRAN_DATE >= '20170701' then 1 end)
over (partition by acct_no order by TRAN_DATE, TRAN_TIME ) as sm_i
from (
Select
Columns
FROM
#BASEtable DTRAN
INNER JOIN sometable
where condition) t) t
where sm_i = 1
order by acc_no
here is the data example, (attached)
Company Acct_no Tran_Date Death_of_date
1 123 20170725 20170702
1 123 20170825 20170702
1 123 20170925 20170702
2 456 20191025 20200101
2 456 20191125 20200101
2 456 20191225 20200101
Result expected: Row no 1, as that is the first transaction for that account after the death_of_date
I am sorting the data based on 20170701, that is it will pick the first transaction happened after this date should be picked up which is working with the above query.
Now, i want to set the value of '20170701' with the dynamic value, ie need the first transaction of every account after its death of date..
I replaced the partition code the below code,
sum(case when tran_Date > = (select death_of_date from #basetable a where a.acct_no = t.acct_no ) then 1 end)
over partition by acct_no order by tran_Date , tran_Time) as sm_i
but getting error saying, subquery retuned more than one result which is not application where using >, = and so on.
Please help to enhance this code in sql server. Appreciate your help in advance!
Assuming two things:
Then you can use window functions and filtering:
select t.*
from (select t.*,
row_number() over (partition by Company, Acct_no order by Tran_Date) as seqnum
from t
where tran_date > death_of_date
) t
where seqnum = 1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.