我有一个(简化的)结果表:
id | Result1 | Result2 | Progress
---------------------------------
1 | 1b | 3c | NULL
2 | 2c | 2a | NULL
3 | 3c | 2b | NULL
4 | P3 | 2c | NULL
5 | 2c | A | NULL
我想根据Result1和Result2列的数字部分(始终是第一个字符)之间的差异来填充Progress列。如果任一结果列的第一个字符不是数字,则Progress列应为NULL。
因此上表的结果应为
3c - 1b = 2
2a - 2c = 0
2b - 3c = -1
2c - P3 = NULL
A - 2c = NULL
感谢您的帮助。
答案 0 :(得分:0)
使用CASE
AND LEFT()
SELECT *,
(CASE WHEN
LEFT(Result1 ,1) - LEFT(Result2 ,1) >=0 OR
LEFT(Result1 ,1) - LEFT(Result2 ,1) <=0
THEN LEFT(Result1 ,1) - LEFT(Result2 ,1)
ELSE NULL END ) `result`
FROM table
编辑
首先检查第一个值是否为数字然后计算
SELECT *,
(CASE WHEN
CONCAT('',LEFT(Result1 ,1) * 1) =0 THEN NULL
WHEN CONCAT('',LEFT(Result2 ,1) * 1) =0 THEN NULL
WHEN LEFT(Result2 ,1) - LEFT(Result1 ,1) >=0 OR
LEFT(Result2 ,1) - LEFT(Result1 ,1) <=0
THEN LEFT(Result2 ,1) - LEFT(Result1 ,1)
ELSE NULL END ) `result`
FROM `progress`
答案 1 :(得分:0)
UPDATE table
SET Progress = IF(Result1 RLIKE '^[0-9]' AND Result2 RLIKE '^[0-9]', Cast(Result1 AS SIGNED) - Cast(Result2 AS SIGNED), NULL);
答案 2 :(得分:0)
感谢那些回复的人,这里的快速反应使我指出了正确的方向 - 这就是我想出的:
UPDATE mytable SET Progress =
CASE
WHEN CAST(Result1 AS SIGNED) > 0 AND CAST(Result2 AS SIGNED) > 0
THEN CAST(Result2 AS SIGNED) - CAST(Result1 AS SIGNED)
ELSE NULL
END
答案 3 :(得分:0)
update table_name
set progress=if(left(Result2,1)regexp'[:alpha:]'=1,null,left(Result2,1))-if(left(Result1,1)regexp'[:alpha:]'=1,null,left(Result1,1)) ;