SQL Case Statement numeric and varcha
SQL
我想将小学分配给 9 年级以下和 9 年级及以上的学年,而 Preschool 是相同的
请尝试以下...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | SELECT Student_Subject_Type_Desc, Class_Year, CASE WHEN Class_Year = 'PreSchool' THEN 'PreSec' WHEN Class_Year = 'Voc Yr1' THEN 'Voc_Yr1' WHEN Class_Year = 'Voc Yr2' THEN 'Voc_Yr2' WHEN ISNUMERIC( Class_Year ) <> 1 THEN NULL WHEN CAST( Class_Year AS INT ) < 9 THEN 'Primary' ELSE 'Secondary' END AS SchType FROM FILNA.dbo.VIEW_FILNA_STUDENTS_SUBJECT ORDER BY Student_Subject_Type_Desc LIMIT 1000 |
我首先测试了
请注意,从您的问题中不清楚如何处理
附录
至于您第二条评论中的第二条语句,您提供的代码是...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | SELECT Student_Subject_Type_Desc, Class_Year, CASE WHEN Class_Year = 'PreSchool' THEN 'PreSec' WHEN Class_Year = 'Voc Yr1' THEN 'Voc_Yr1' WHEN Class_Year = 'Voc Yr2' THEN 'Voc_Yr2' WHEN ISNUMERIC( Class_Year ) <> 1 THEN NULL WHEN CAST( Class_Year AS INT ) < 9 THEN 'Primary' ELSE 'Secondary' END AS SchType FROM [FILNA].[dbo].[Student_Subject_Desc] WHERE SchType = 'Primary' ORDER BY Student_Subject_Type_Desc |
因为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | SELECT Student_Subject_Type_Desc, Class_Year, SchType FROM ( SELECT Student_Subject_Type_Desc, Class_Year, CASE WHEN Class_Year = 'PreSchool' THEN 'PreSec' WHEN Class_Year = 'Voc Yr1' THEN 'Voc_Yr1' WHEN Class_Year = 'Voc Yr2' THEN 'Voc_Yr2' WHEN ISNUMERIC( Class_Year ) <> 1 THEN NULL WHEN CAST( Class_Year AS INT ) < 9 THEN 'Primary' ELSE 'Secondary' END AS SchType FROM FILNA.dbo.VIEW_FILNA_STUDENTS_SUBJECT ) AS SchTypeFinder WHERE SchType = `Primary` ORDER BY Student_Subject_Type_Desc LIMIT 1000 |
但是,这比将语句更改为这种形式效率低...
1 2 3 4 5 6 7 8 | SELECT Student_Subject_Type_Desc, Class_Year, 'Primary' AS SchType FROM [FILNA].[dbo].[Student_Subject_Desc] WHERE ISNUMERIC( Class_Year ) = 1 AND CAST( Class_Year AS INT ) < 9 ORDER BY Student_Subject_Type_Desc LIMIT 1000 |
这只会
如果您有任何问题或意见,请随时发表相应的评论。
进一步阅读
使用 sql 查询将字符串转换为 int(关于将字符串转换为
https://docs.microsoft.com/en-us/sql/t-sql/functions/isnumeric-transact-sql(关于