从mysql中的一行中的特定列中查找last not null值的列名

时间:2014-11-28 10:16:43

标签: mysql sql select case conditional-statements

我有一个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

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

2 个答案:

答案 0 :(得分:0)

试试这个:

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;

答案 1 :(得分:0)

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'

侨!