首页 > 解决方案 > SQLite - 在With子句之后返回不为空的数据的列名称

问题描述

我正在尝试从查询中获取列名。在我的例子中,列名是电池电压,并不是每个 ID 都与每个电池电压兼容,所以我有第二个表来映射哪些 ID 具有哪些电压。如果它为空,则它不支持该电压。我想对该 ID 的电压进行最终查询。所以有数据的列名。

我尝试了以下方法,希望它会返回两列,names 和 notnull,这样我就可以对其进行最后一次查询并过滤掉空数据并获得结果电池电压。但以下没有返回任何错误。

 WITH previous_results AS(SELECT *
      FROM Table1
      JOIN Table2
      ON Table1.table2id = Table2.table2id
), second_results AS( SELECT *
  FROM previous_results
  WHERE previous_results.id= '2'
  )

 SELECT c.name, c.[notnull] FROM pragma_table_info('second_results') c ;
  

这种方式可能行不通,所以有人可以帮我解决吗?我提供了一个视觉效果,因此您可以看到我最终要查找的内容。在此处输入图像描述

标签: sqlsqliteinner-joinunpivotunion-all

解决方案


看起来您想要给定的table2具有非空值的列的名称id。如果是这样,您可以使用union all

select '12' as colname from table2 where tbl2_id = 2 and col_12 is not null
union all select '24'  from table2 where tbl2_id = 2 and col_24 is not null
union all select '48'  from table2 where tbl2_id = 2 and col_48 is not null

我假设列名col_12col_24并且col_48table2.

如果你真的想过滤idfrom table1,那么你可以join,然后将过滤移动id到外部查询的where子句:

select t2.colname
from (
    select tbl2_id, '12' as colname from table2 where col1_12 is not null
    union all select tbl2_id, '24'  from table2 where col1_24 is not null
    union all select tbl2_id, '48'  from table2 where col1_48 is not null
) t2
inner join table1 t1 on t1.tbl2_id = t2.tbl2_id
where t1.id = 2

推荐阅读