我有一张有价值观的表格。我正在尝试创建一个新列,其行值将取决于现有列的行。例如,在下表中,如果从索引6到索引7的id列的substr大于10,那么该行的新列的值应该是索引1-4处的id的子字符串< em>连字符 substr(id,1,4)+1。否则值应为substr(id,1,4)-1 连字符 substr(id,1,4)。
id New Column Name
M20061012 2006-2007 Jude
K20070212 2006-2007 Anne
D20071214 2007-2008 John
以下是表格每一行的算法:
if substr(id, 5, 1) < 10
New Column value at that row = substr(id, 1, 4) - substr(id, 1, 4)+1
else
New Column value at that row = substr(id, 1, 4)-1 - substr(id, 1, 4)
任何帮助将不胜感激 感谢
修改 所以我按照@scwagner
的建议尝试了这个SELECT
id,
(CASE WHEN CONVERT(SUBSTR(id,6,2), SIGNED) < 10
THEN CONCAT(CONVERT(SUBSTR(id, 2, 4),SIGNED)-1,'-',CONVERT(SUBSTR(id, 2, 4),SIGNED))
ELSE CONCAT(CONVERT(SUBSTR(id, 2, 4),SIGNED),'-',CONVERT(SUBSTR(id, 2, 4),SIGNED)+1) END) AS `New Column`,
Name
FROM new
其中new是表的名称。但是这会返回一个包含所有行值= BLOB的列。 我该如何解决这个问题?
答案 0 :(得分:1)
您可能希望在更多数据上对此进行测试,但这适用于MySQL 5.1.41-3ubuntu12.8以及您提供的测试数据:
SELECT
id,
(CASE WHEN CONVERT(SUBSTR(id,6,2), SIGNED) < 10 THEN CONCAT(CONVERT(SUBSTR(id, 2, 4),SIGNED)-1,'-',CONVERT(SUBSTR(id, 2, 4),SIGNED)) ELSE CONCAT(CONVERT(SUBSTR(id, 2, 4),SIGNED),'-',CONVERT(SUBSTR(id, 2, 4),SIGNED)+1) END) AS `New Column`,
Name
FROM
<your table>
答案 1 :(得分:0)
想出来:
SELECT
id,
(CASE WHEN CONVERT(SUBSTR(id,6,2), SIGNED) < 10
THEN CONCAT(CAST(CONVERT(SUBSTR(id, 2, 4),SIGNED)-1 AS CHAR),'-',CAST(CONVERT(SUBSTR(id, 2, 4),SIGNED) AS CHAR))
ELSE CONCAT(CAST(CONVERT(SUBSTR(id, 2, 4),SIGNED) AS CHAR),'-',CAST(CONVERT(SUBSTR(id, 2, 4),SIGNED)+1) AS CHAR) END) AS `New Column`,
Name
FROM new