我有一个 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.
任何帮助将不胜感激。提前致谢!