如何获取空值的表中列名?

3

考虑以下表格:

--------------------------------
ID   | ColA    | ColB   | ColC
--------------------------------
1    | ABC     |        |
2    |         | XYZ    |
3    | PQR     |        |
4    | MNO     | PQR    |

我需要获取表格中ID = 1时的第一个空闲列。如何实现呢?

例如:

如果ID = 1,下一个空闲列是ColB
如果ID = 2,下一个空闲列是ColA
如果ID = 3,下一个空闲列是ColB
如果ID = 4,下一个空闲列是ColC


看起来是一个非常奇怪的数据库架构。你应该考虑改变数据库设计。 - Rafael T
@Rafael - 这很奇怪,但我必须这么做。我不能更改模式。 - user1556433
我想不出任何符合您要求的查询。我猜您必须手动处理这些数据。 - Rafael T
@RafaelT - 你的意思是说,无法根据某些条件通过 SQL 查询获取列名。 :( - user1556433
@NareshKumar - 很简单。看看我的答案。 - Fathah Rehman P
4个回答

1
对于sql-server;(如果您还想考虑空字符串(''),那么使用nullif(colName,'') is null)
Select Id, case when colA is null then 'colA'
                when colB is null then 'colB'
                when colC is null then 'colC'
                ...
           end freeCol
from yourTable

1
如果您想要列的名称,可以这样做:
SQL> select id, cola, colb, colc,
  2         coalesce(nvl2(cola, '', 'COLA'),
                     nvl2(colb, '', 'COLB'),
                     nvl2(colc, '', 'COLC')) first_free_col
  3    from tab;

        ID COL COL COL FIRST_FREE_COL
---------- --- --- --- --------------------------------
         1 ABC         COLB
         2     XYZ     COLA
         3 PQR         COLB
         4 MNO PQR     COLC

或者情况
SQL> select id, cola, colb, colc,
  2         case when cola is null then 'COLA'
  3          when colb is null then 'COLB'
  4          when colc is null then 'COLC'
  5         end first_free_col
  6    from tab;

        ID COL COL COL FIRST_FREE_COL
---------- --- --- --- --------------------------------
         1 ABC         COLB
         2     XYZ     COLA
         3 PQR         COLB
         4 MNO PQR     COLC

1

试试这个:

select case 
when ColA is not null then 'ColA'
when ColB is not null then 'ColB'
when ColC is not null then 'ColC'

End FirstCol

from test

SQL Fiddle

->

{{链接1:SQL Fiddle}}


1
你可以在MySQL中使用以下查询。
select ID,if(colA is null,'colA',(if(colB is null,'colB',
(if(colC is null,'colC','no column is null'))))) as Result  from your_table_name

对于您的示例表格,如果您执行我的查询,您将得到以下结果。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接