SQL 根据另一列的值选择特定列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3338710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:57:17  来源:igfitidea点击:

Select a specific column based on another column's value

sqlsql-servertsql

提问by BrunoLM

I have a table like this

我有一张这样的桌子

ID | Type | Val0 | Val1
1  |  0   |  A   | NULL
2  |  1   | NULL |  B

I need to select Val0when the type is 0, and Val1when the type is 1, and ValNwhen type is N...

我需要选择Val0什么时候类型是0,Val1什么时候类型是1,ValN什么时候类型是N...

How can I do that?

我怎样才能做到这一点?

回答by dcp

SELECT CASE
          WHEN Type = 0 THEN Val0
          WHEN Type = 1 Then Val1
          .
          .
          WHEN Type = N Then ValN
       END 
  FROM tbl

回答by OMG Ponies

The way I read this, you need to use UNION:

按照我的阅读方式,您需要使用 UNION:

SELECT a.val0
  FROM TABLE a
 WHERE a.type = 0
UNION ALL
SELECT a.val1
  FROM TABLE a
 WHERE a.type = 1
UNION ALL ...

UNION ALL doesn't remove duplicates, and is faster than UNION (because it removes duplicates).

UNION ALL 不删除重复项,并且比 UNION 更快(因为它删除重复项)。

Doing this dynamically is possible.

动态执行此操作是可能的。

回答by cypheon

For low values of N, you can do it ad-hoc using the CASE statement, like CASE Type WHEN 0 THEN Val0 WHEN 1 THEN Val1 END. If your N is bigger, you should probably normalize your database (i.e. put ID => ValN mappings in a different table).

对于 N 的低值,您可以使用CASE 语句临时执行,例如CASE Type WHEN 0 THEN Val0 WHEN 1 THEN Val1 END。如果您的 N 更大,您可能应该规范化您的数据库(即将 ID => ValN 映射放在不同的表中)。