【问题标题】:Find the column name of last not null value from a particular columns in a row in mysql从mysql中一行中的特定列中查找最后一个非空值的列名
【发布时间】:2015-01-26 23:33:46
【问题描述】:

我有一个mysql表是这样的

  ID    status1        status2       status3         status4      date   

  1      busy           null        callagain         null      2014-11-28
  2      null           null          busy            null      2014-11-26
  3   notreachable      busy          null            null      2014-11-26

其中 ID 是主键。 我想从status1,status2,status3,status4列中获取一行中最后一个非空值的列名,结果是这样的

   ID    status
   1     status3
   2     status3
   3     status2

我还需要一个带有此查询的 where cluase,其中此结果状态 ='any_value'。 请帮帮我。

【问题讨论】:

    标签: mysql sql select case conditional-statements


    【解决方案1】:

    试试这个:

    SELECT a.id, (CASE WHEN a.status4 IS NOT NULL THEN 'status4' 
                       WHEN a.status3 IS NOT NULL THEN 'status3' 
                       WHEN a.status2 IS NOT NULL THEN 'status2' 
                       WHEN a.status1 IS NOT NULL THEN 'status1' 
                       ELSE NULL 
                  END) AS colStatus
    FROM tableA a;
    

    第二个问题:这个结果状态='any_value'。

    SELECT a.id, a.status 
    FROM (SELECT a.id, (CASE WHEN a.status4 IS NOT NULL THEN 'status4' 
                             WHEN a.status3 IS NOT NULL THEN 'status3' 
                             WHEN a.status2 IS NOT NULL THEN 'status2' 
                             WHEN a.status1 IS NOT NULL THEN 'status1' 
                             ELSE NULL 
                       END) AS colSTATUS
          FROM tableA a
         ) AS A 
    WHERE a.status IS NOT NULL;
    

    【讨论】:

      【解决方案2】:
      SELECT *
      FROM ( SELECT ID ,
                COALESCE( CASE
                              WHEN status4 IS NOT NULL THEN 'status4'
                              ELSE NULL
                          END ,
                          CASE
                              WHEN status3 IS NOT NULL THEN 'status3'
                              ELSE NULL
                          END ,
                          CASE
                              WHEN status2 IS NOT NULL THEN 'status2'
                              ELSE NULL
                          END ,
                          CASE
                              WHEN status1 IS NOT NULL THEN 'status1'
                              ELSE NULL
                          END ,
                          NULL ) AS colstatus
             FROM table1 ) AS DERIVEDTABLE
      WHERE colstatus = 'status3'
      

      哎呀!

      【讨论】:

      • 谢谢。但它不起作用。我将 status4 作为所有数据的字段名称
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2021-10-01
      • 2011-04-16
      • 1970-01-01
      相关资源
      最近更新 更多