我基本上有这个表,其中22出现在A或B中:
A | B
---| ---
22 | 0
32 | 22
45 | 22
22 | 5
我想从这个表中创建一个新列,该列只有非22行的值,例如
C
-
0
32
45
5
我该怎么做?
编辑:上表来自此声明
SELECT A,B FROM table
WHERE (A = '22' OR B = '22')
答案 0 :(得分:1)
您可以使用case
表达式生成此输出:
SELECT CASE a WHEN 22 THEN b ELSE a END AS c
FROM mytable
WHERE 22 IN (a, b)
答案 1 :(得分:1)
你也可以试试这个:
SELECT CASE WHEN a = 22 AND b=22 THEN 0 WHEN a = 22 and b != 22 THEN b ELSE a END c
FROM #comm
WHERE 22 IN (a,b)
如果两者都有22,则它将返回0,或者您可以更改值
答案 2 :(得分:0)
SELECT A AS C FROM MYTABLE WHERE A != 22
UNION
SELECT B AS C FROM MYTABLE WHERE B != 22
UNION删除重复项
答案 3 :(得分:0)
首先,您必须在表格中添加C列,这就是您的操作方法:
ALTER TABLE YourTableName
ALTER COLUMN C decimal
然后,您从A列,B列中检索值并将它们插入C:
INSERT INTO YourTableName(C)
SELECT A,B
FROM YourTableName WHERE A<>22 and B<>22
答案 4 :(得分:0)
ALTER TABLE table_name
ALTER COLUMN c INT
UPDATE table_name
SET c= CASE WHEN a<>22 THEN a ELSE b END
答案 5 :(得分:0)
这样的事情?
--drop table ##t1
select *
into ##t1
from(
select 'a1'c1,'b1'c2 union all
select 'a2'c1,'b2'c2 union all
select 'a3'c1,'b3'c2 union all
select 'a4'c1,'a3'c2 union all
select 'a3'c1,'b4'c2 union all
select 'a5'c1,'b5'c2
)t
select *,
case when t2.c1 is null then t1.c1 else t1.c2 end c3
from ##t1 t1
left join
(
select *
from
(
select distinct c1
from ##t1
)t1
join
(
select distinct c2
from ##t1
)t2
on t1.c1=t2.c2
)t2
on t1.c1=t2.c1
这是一个通用的解决方案