SQL可以选择列名作为值

时间:2016-10-21 20:08:49

标签: sql

这是我的桌子 Here is my table

我想选择如下 The selection I would like to have

tch_col将获取列值不为0的列名称,如果全部为0,则将值设为19。

我们可以在SQL中执行此操作吗?

请在此处检查第97行enter image description here

结果应为enter image description here

第一个答案可能不起作用但仍然如此 谢谢

2 个答案:

答案 0 :(得分:1)

从评论中讨论:这是针对SQL Server的;因此,使用视图创建19列,然后使用UNPIVOT运算符可以简化操作。

标准SQL的原始答案如下:

您可以获得您描述的结果(对于大多数主要的SQL数据库;如果您使用旧的或模糊的东西,这可能不起作用)。

但它并不像选择列名那么漂亮。以下SQL依赖于表中的特定列;之后看笔记。

如果你需要每个非0值的记录,它将会非常糟糕。

SELECT tch_function, tch_part, 9
  FROM your_table
 WHERE tch_col_09 <> 0
UNION ALL
SELECT tch_function, tch_part, 10
  FROM your_table
 WHERE tch_col_10 <> 0
-- you can see where this is going, right?
-- union in another select for each column

这里的问题是标准SQL并不适合从每个输入行创建未确定数量的结果行,而不是在连接期间。

现在,如果您可以了解包含9到19之间数字的单个列的关系,那么您可以与其进行交叉连接,然后过滤掉您不想要的行({{1 }});但它仍然很麻烦,不是吗?如果你决定走这条路,你可以使用DB2 VALUES子查询,临时表或其他什么来获得这样的关系......

如果您可以假设只有一列具有非0值,或者如果您对包含第一个非0值的列的名称感到满意,则& #39; d不那么难看:

WHERE (your_table.tch_col_09<>0 AND ref.value=9) OR ... OR (your_table.tch_col_09=0 AND ... AND your_table.tch_col_18=0 AND ref.value=19)

case结构将返回第一个匹配的THEN子句的值,如果没有THEN子句匹配,则返回19。

但听起来好像不会。

最后 - 如果要更改表中的TCH_COL_n列,则必须更改这些查询中的任何一个;至少一个好的关系表结构应该导致一组相当静态的列。

更重要的是,如果您可以更改表格结构或使用SQL之外的处理语言,那么您的表现会更好。

答案 1 :(得分:1)

使用UNION整理多个条目

SELECT tch_function,tch_part,9 AS tch_col FROM TCH WHERE tch_col_09 > 0
UNION
SELECT tch_function,tch_part,10 AS tch_col FROM TCH WHERE tch_col_10 > 0
UNION
SELECT tch_function,tch_part,11 AS tch_col FROM TCH WHERE tch_col_11 > 0
UNION
SELECT tch_function,tch_part,12 AS tch_col FROM TCH WHERE tch_col_12 > 0
UNION
SELECT tch_function,tch_part,13 AS tch_col FROM TCH WHERE tch_col_13 > 0
UNION
SELECT tch_function,tch_part,14 AS tch_col FROM TCH WHERE tch_col_14 > 0
UNION
SELECT tch_function,tch_part,15 AS tch_col FROM TCH WHERE tch_col_15 > 0
UNION
SELECT tch_function,tch_part,16 AS tch_col FROM TCH WHERE tch_col_16 > 0
UNION
SELECT tch_function,tch_part,17 AS tch_col FROM TCH WHERE tch_col_17 > 0
UNION
SELECT tch_function,tch_part,18 AS tch_col FROM TCH WHERE tch_col_18 > 0
UNION
SELECT tch_function,tch_part,19 AS tch_col FROM TCH 
WHERE tch_col_09 = 0 AND  tch_col_10 = 0 AND tch_col_11 = 0 
  AND tch_col_12 = 0 AND tch_col_13 = 0 AND tch_col_14 = 0
  AND tch_col_15 = 0 AND tch_col_16 = 0 AND tch_col_17 = 0
  AND tch_col_18 = 0
ORDER BY 1,2