sql: select 仅来自另一列的最大值、最小值、中间值,其余为空
sql: select only max, min, mid from another column, with the rest as null
我正在尝试根据现有列在 table 中创建一个新列。在下面的示例中,我想 select "Amount" 的最大值、最小值和中间值按 "Sequence" 排序,按 "Person"
划分
有人能帮忙吗?谢谢!
数据以逗号分隔。
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
我会使用条件聚合来做到这一点。您确实需要更多信息才能获得中间值:
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;
编辑:
哦,我明白了,您希望其余的都为 NULL -- 而不仅仅是每个人的三个值。那么:
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;
我正在尝试根据现有列在 table 中创建一个新列。在下面的示例中,我想 select "Amount" 的最大值、最小值和中间值按 "Sequence" 排序,按 "Person"
划分有人能帮忙吗?谢谢!
数据以逗号分隔。
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
我会使用条件聚合来做到这一点。您确实需要更多信息才能获得中间值:
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;
编辑:
哦,我明白了,您希望其余的都为 NULL -- 而不仅仅是每个人的三个值。那么:
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;