I'm trying to create a new column in a table based on an existing column. In the example below, I want to select the max, min, and mid of "Amount" order by the "Sequence" number, partition by "Person"
Can anyone help? Thank you!
The data in comma delimited.
Person,Sequence,Amount
A,1,1908
A,2,3896
A,3,2726
A,4,4730
A,5,4174
A,6,3156
A,7,3360
A,8,2439
B,1,1768
B,2,1967
B,3,1841
B,4,1534
B,5,729
B,6,2434
B,7,3502
B,8,108
I would do this using conditional aggregation. You do need a bit more information to get the middle value:
select person, min(amount), max(amount)
max(case when 2 * sequence in (cnt, cnt + 1) then amount end) as middle_val
from (select t.*,
count(*) over (partition by person) as cnt
from t
) t
group by person;
EDIT:
Oh, I see, you want the rest as NULL -- not just the three values per person. Then:
select t.*,
(case when sequence in (1, floor(cnt / 2), maxseq) then amount
end) as new_amount
from (select t.*,
count(*) over (partition by person) as cnt,
max(sequence) over (partition by person) as maxseq
from t
) t;
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.