派生列,其中包含按日期排序的列名

时间:2019-01-03 00:56:05

标签: mysql sql sorting

我想创建一个如下所示的派生列,而不使用If-Else语句。

enter image description here

我有x,y,z列,它们都是日期。我想获得第四列,该列显示ascending中的字段顺序,而不使用If-Else or Case when。有可能吗?

3 个答案:

答案 0 :(得分:1)

在您的样本数据中,我想3d行结果是'z,y,x'对吗?

select xyz.*, t.derived_column from (
  select s_n, group_concat(type order by value) as derived_column from 
  ( 
    select s_n, 'x' as type, x as value from xyz
    union all
    select s_n, 'y' as type, y as value from xyz
    union all
    select s_n, 'z' as type, z as value from xyz
  ) as xyz1  
  group by s_n
  ) as t
inner join xyz
on t.s_n = xyz.s_n

请参见demo

答案 1 :(得分:1)

在没有聚合的情况下执行此操作非常棘手。但是有可能。当然,真正的挑战是获取中间元素-尤其是在没有caseif()的情况下。但是,这只是一个挑战。

select concat_ws(',',
                 highest,
                 coalesce(elt(field('x', highest, least) + 1, 'x'), elt(field('y', highest, least) + 1, 'y'), elt(field('z', highest, least) + 1, 'z')),
                 lowest
                )
from (select x.*,
             elt(field(greatest(x, y, z), x, y, z), 'x', 'y', 'z') as highest,
             elt(field(least(x, y, z), x, y, z), 'x', 'y', 'z') as least
      from (select 'a' as a, 1 as x, 2 as y, 3 as z union all
            select 'b' as a, 4 as x, 2 as y, 3 as z
           ) t
     ) t;

您实际上可以在不使用子查询的情况下表示中间值表达式,但这要复杂得多。上面使用整数,但是逻辑与日期或字符串也一样。

这也可以写成:

select elt(field(concat(highest, lowest), 'xy', 'xz', 'yz', 'yx', 'zx', 'zy'), 'x,z,y', 'x,y,z', 'y,x,z', 'y,z,x', 'z,y,x', 'z,x,y')
from (select t.*,
             elt(field(greatest(x, y, z), x, y, z), 'x', 'y', 'z') as highest,
             elt(field(least(x, y, z), x, y, z), 'x', 'y', 'z') as lowest
      from (select 'a' as a, 1 as x, 2 as y, 3 as z union all
            select 'b' as a, 4 as x, 2 as y, 3 as z
           ) t
     ) t

答案 2 :(得分:0)

对于xyz列中的每一个,选择相应的字符文字,通用名称的列别名以及其他原样。合并结果。现在,从联合中选择其他列,并将group_concat()ORDER BY表达式一起使用以获取排序列表。

SELECT x.s_n,
       x.x,
       x.y,
       x.z,
       group_concat(x.c
                    ORDER BY x.d) derived_column
       FROM (SELECT t.s_n,
                    t.x,
                    t.y,
                    t.z,
                    'x' c,
                    t.x d
                    FROM elbat t
             UNION ALL
             SELECT t.s_n,
                    t.x,
                    t.y,
                    t.z,
                    'y' c,
                    t.y d
                    FROM elbat t
             UNION ALL
             SELECT t.s_n,
                    t.x,
                    t.y,
                    t.z,
                    'z' c,
                    t.z d
                    FROM elbat t) x
       GROUP BY x.s_n,
                x.x,
                x.y,
                x.z;