Sql 如何按大小对列进行排序

Sql 如何按大小对列进行排序,sql,amazon-redshift,Sql,Amazon Redshift,我有一张表,有长度、宽度和高度列,我想订购它们,这样我就有了一张新表,名为“最大尺寸”、“中间尺寸”、“最小尺寸”,或者是“一般尺寸”、“第一尺寸”、“第二尺寸”等 我知道在红移中我们有最大和最小的功能,但这不会让我获得中间位置。在这种情况下,我想对3个维度进行排序,我可以在子查询中获得3个维度中的最大值和3个维度中的最小值,然后使用一个案例和条件来获得中间值,但我想知道是否有更简单/更有效的方法来实现这一点这是一种痛苦。一种方法是使用复杂的事例表达式。另一种方法是拆分行并重新聚合: selec

我有一张表,有长度、宽度和高度列,我想订购它们,这样我就有了一张新表,名为“最大尺寸”、“中间尺寸”、“最小尺寸”,或者是“一般尺寸”、“第一尺寸”、“第二尺寸”等


我知道在红移中我们有最大和最小的功能,但这不会让我获得中间位置。在这种情况下,我想对3个维度进行排序,我可以在子查询中获得3个维度中的最大值和3个维度中的最小值,然后使用一个案例和条件来获得中间值,但我想知道是否有更简单/更有效的方法来实现这一点

这是一种痛苦。一种方法是使用复杂的事例表达式。另一种方法是拆分行并重新聚合:

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是一个列,它像主键一样唯一地标识每一行。

这是一个难题。一种方法是使用复杂的事例表达式。另一种方法是拆分行并重新聚合:

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是一个列,它像主键一样唯一地标识每一行。

仅对三个值来说并不难。你有最大值,最小值,另外一个值的和减去两个:

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;

只有三种价值观,这并不难。你有最大值,最小值,另外一个值的和减去两个:

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;