我有一些SQL从正常的表中选择列。但是,我的一个列(u.cmc_rti_type)是一个数字,我希望它输出文本。我想我需要某种if语句。这是我的sql:
SELECT '', s.student_number, s.lastfirst, s.grade_level, t.TEACHER, u.cmc_rti_tier, u.cmc_rti_type
FROM students s
JOIN u_def_ext_students u
ON u.studentsdcid = s.dcid
LEFT JOIN cmc_homeroom_teacher t
ON s.dcid = t.dcid
WHERE u.cmc_rti_tier <> 0
ORDER BY s.lastfirst
如果u.cmc_rti_type为1,那么我希望它输出'Reading' 如果u.cmc_rti_type为2,那么我希望它输出'Math' 如果u.cmc_rti_type为3,那么我希望它输出'Enrichment' 如果u.cmc_rti_type为4,那么我希望它输出'Both Math&amp;读“
答案 0 :(得分:1)
您可以在以下内容中使用CASE
:
SELECT '', s.student_number, s.lastfirst, s.grade_level, t.TEACHER, u.cmc_rti_tier,
CASE u.cmc_rti_type WHEN 1 THEN 'Reading'
WHEN 2 THEN 'Math'
WHEN 3 THEN 'Enrichment'
WHEN 4 THEN 'Both Math & Reading'
END AS Etc
FROM students s
JOIN u_def_ext_students u
ON u.studentsdcid = s.dcid
LEFT JOIN cmc_homeroom_teacher t
ON s.dcid = t.dcid
WHERE u.cmc_rti_tier <> 0
ORDER BY s.lastfirst
答案 1 :(得分:1)
您可以使用CASE
:
SELECT '', s.student_number, s.lastfirst, s.grade_level, t.TEACHER,
u.cmc_rti_tier,
CASE u.cmc_rti_type
WHEN 1 THEN 'Reading'
WHEN 2 THEN 'Math'
WHEN 3 THEN 'Enrichment'
WHEN 4 THEN 'Both Math & Reading'
ELSE NULL
END AS cmc_rti_type
FROM students s
JOIN u_def_ext_students u
ON u.studentsdcid = s.dcid
LEFT JOIN cmc_homeroom_teacher t
ON s.dcid = t.dcid
WHERE u.cmc_rti_tier <> 0
ORDER BY s.lastfirst
如果您使用 SQL Sever 2012 + ,则可以使用CHOOSE
:
CHOOSE(u.cmc_rti_type, 'Reading', 'Math', 'Enrichment', 'Both Math & Reading') AS cmc_rti_type
的 LiveDemo
强>
答案 2 :(得分:1)
您需要case
:
SELECT CASE u.cmc_rti_type
WHEN 1 then 'Reading'
WHEN 2 then 'Math'
WHEN 3 then 'Enrichment'
WHEN 4 then 'Both Math & Reading' END,
s.student_number,
s.lastfirst,
s.grade_level,
t.TEACHER,
u.cmc_rti_tier,
u.cmc_rti_type
FROM students s
JOIN u_def_ext_students u ON u.studentsdcid = s.dcid
LEFT JOIN cmc_homeroom_teacher t ON s.dcid = t.dcid
WHERE u.cmc_rti_tier <> 0
ORDER BY s.lastfirst
答案 3 :(得分:1)
而且,对于完全不同的东西。
如果您具有必要的权限,则可以使用查找表来执行case语句的工作。这将允许您在将来添加更多选择,而无需查找执行此case语句的所有代码。
CREATE TABLE rti_type_lookup
(
rti_type_value int not null,
rti_type_label varchar(100) not null
)
INSERT INTO rti_type_lookup (rti_type_value, rti_type_label)
VALUES (1, 'Reading'),
(2, 'Math'),
(3, 'Enrichment'),
(4, 'Both Math & Reading')
现在,当您需要获取文本版本时,您可以进行加入。而且,将来,您只需在rti_type_lookup
表中添加新的查找值,而不是更新SELECT
语句。
SELECT '', s.student_number, s.lastfirst, s.grade_level, t.TEACHER,
u.cmc_rti_tier, rti_type_label AS cmc_rti_type
FROM students s
JOIN u_def_ext_students u
ON u.studentsdcid = s.dcid
JOIN rti_type_lookup l
ON u.cmc_rti_type = l.rti_type_value
LEFT JOIN cmc_homeroom_teacher t
ON s.dcid = t.dcid
WHERE u.cmc_rti_tier <> 0
ORDER BY s.lastfirst