在MySQL中无法正确使用REPLACE功能

时间:2013-03-29 12:00:05

标签: mysql

我有一个SQL表,其列为State_Code,School_Code和School_Type。

示例数据:

State_Code    School_Code     School_Type
 01            01014874        1
 01            01018790        2
 1             10189900        1
 1             10277689        1

*(注意:School_Code的第1和第2位是实际的州代码,而第3和第4位是该特定州的District_Code)*

现在,如果我触发此查询:

Select COUNT(School_Code) from Table1 where State_Code='1'+0;

它将返回州内的学校数量,代码为“1”;即 4 ;

但是,如果我想要检索一个州DISTRICT-WISE的学校数量;我会触发这个查询:

Select State_Code,SUBSTRING(School_Code,3,2) AS District_Code,COUNT(School_Code) AS Number_of_Schools_In_District FROM Table1 GROUP BY State_Code+0;

此查询返回此输出:

State_Code     District_Code      Number_of_Schools_In_District
   01               01                         2
   1                18                         1
   1                27                         1

但正确的输出是:

State_Code     District_Code      Number_of_Schools_In_District
   01               01                         3
   1                02                         1

这是由于用户在SQL表中为列School_Code输入的数据不正确。状态'1'和'01'实际上是相同的状态,即'01'。但由于第3行和第4行中的School-Code不以'0'开头,这导致输出中的行为不正确。

所以要解决这个问题,我将不得不使用这个逻辑:

*If number of characters in State_Code is 1 and School_Code does not start with '0', then a '0' should be prefixed to the School_Code value to get the correct District_Code value.*

我试过了:

Select State_Code,SUBSTRING(School_Code,3,2) AS District_Code,COUNT(School_Code) AS     Number_of_Schools_In_District FROM Table1 WHERE IF CHARACTER_LENGTH(State_Code)=1 AND School_Code NOT LIKE '0%' THEN REPLACE(School_Code,School_Code,CONCAT(0,School_Code)) END IF GROUP BY State_Code+0, SUBSTRING(School_Code,3,2)+0;

我的期望是,如果State_code中的任何值是单个数字且其相应的学校代码不以'0'开头,那么这将向其追加'0',然后计算第3和第4位的区码。但这不会发生。我仍然得到错误。

Note: I don't want to update original SQL table values.

任何帮助将不胜感激。在此先感谢!

1 个答案:

答案 0 :(得分:0)

尝试以下查询

Select State_Code, IF(CHARACTER_LENGTH(State_Code)=1, SUBSTRING(School_Code,2,2), SUBSTRING(School_Code,3,2)) AS District_Code,COUNT(School_Code) AS     Number_of_Schools_In_District FROM Table1 WHERE GROUP BY State_Code+0, SUBSTRING(School_Code,3,2)+0;