我有一个具有长度,宽度和高度列的表,我想对它们进行排序,以便有一个名为great_dim,mid_dim,min_dim的新表,或者用于常规表,1st_dim,2nd_dim等
我知道在redshift中我们具有最大和最小的功能,但这不会让我处于中间位置。对于这种情况,我想订购3个维度,我可以在子查询中获得3个维度中的最大值和3个维度中的最小值,然后使用和条件来获取中间值,但是我想知道是否有更简单/更有效的方法方式
答案 0 :(得分:2)
这很痛苦。一种方法是复杂的case
表达式。另一个是将行分开并重新聚合:
select pk,
max(case when seqnum = 1 then dim end) as dim_1,
max(case when seqnum = 2 then dim end) as dim_2,
max(case when seqnum = 3 then dim end) as dim_3
from (select pk, row_number() over (order by dim desc) as seqnum
from (select pk, length as dim from t
union all
select pk, width as dim1 from t
union all
select pk, height as dim1 from t
) t
) t
group by pk;
pk
是一列,可唯一标识每一行(如主键)。
答案 1 :(得分:2)
对于只有三个值,这并不困难。您有GREATEST
,LEAST
,总和减去两个值即得出另一个值:
select
greatest(length, width, height) as greatest_dim,
length + width + height - greatest(length, width, height)
- least(length, width, height) as mid_dim,
least(length, width, height) as min_dim
from mytable;