在SQL中添加一个临时列,其中值取决于另一列 [英] add a temporary column in SQL, where the values depend from another column
本文介绍了在SQL中添加一个临时列,其中值取决于另一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这张桌子:
ID | name | result |
--------------------
1 | A | 1 |
--------------------
2 | B | 2 |
--------------------
3 | C | 1 |
--------------------
1 | A | 2 |
--------------------
4 | E | 2 |
--------------------
我想在| result |旁边添加一个新的临时列,其中result = 1的值应为100,而result = 2的值应为80,因此应如下所示:
I want to add a new temporary column next to |result|, and where result=1 the value should be 100, and where result=2 the value should be 80 so it should look like this:
ID | name | result | NewColumn|
-------------------------------
1 | A | 1 | 100 |
-------------------------------
2 | B | 2 | 80 |
-------------------------------
3 | C | 1 | 100 |
-------------------------------
1 | A | 2 | 80 |
-------------------------------
4 | E | 2 | 80 |
-------------------------------
如何在SQL中查询呢?
How can I query this in SQL ?
推荐答案
使用 SELECT
的列列表中的CASE
表达式-像这样:
Use a CASE
expression in your SELECT
's column list - something like this:
SELECT
ID,
name,
result,
CASE
WHEN result = 1 THEN 100
WHEN result = 2 THEN 80
ELSE NULL
END AS NewColumn
FROM YourTable
根据需要添加其他WHEN
表达式或更改ELSE
表达式.
Add additional WHEN
expressions or alter the ELSE
expression as needed.
这篇关于在SQL中添加一个临时列,其中值取决于另一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文