sql - 我需要为每个字段重写 case 语句吗?

标签 sql sql-server tsql

两列的 case 条件是相同的。在下面的语句中我使用了两次但是对于不同的列,有没有其他方法可以不重复条件两次??

case [CPHIL_AWD_CD]
                     when ' ' then 'Not Applicable/ Not a Doctoral Student'
                     when 'X' then 'Not Applicable/ Not a Doctoral Student'
                     when 'N' then 'NO'
                     when 'Y' then 'YES'
                end as CPHIL_AWD_CD

              ,case [FINL_ORAL_REQ_CD] 
                     when ' ' then 'Not Applicable/ Not a Doctoral Student'
                     when 'X' then 'Not Applicable/ Not a Doctoral Student'
                     when 'N' then 'NO'
                     when 'Y' then 'YES'
                end as FINL_ORAL_REQ_CD

最佳答案

只需使用映射创建一个表(临时?)

CREATE TABLE [Constants]
(
    [ID] nvarchar(1) PRIMARY KEY,
    [Text] nvarchar(max)
)
INSERT INTO [Constants] VALUES (' ', 'Not Applicable/ Not a Doctoral Student')
INSERT INTO [Constants] VALUES ('X', 'Not Applicable/ Not a Doctoral Student')
INSERT INTO [Constants] VALUES ('N', 'No')
INSERT INTO [Constants] VALUES ('Y', 'Yes')

并执行内部连接

SELECT C1.Text AS CPHIL_AWD_CD, C2.Text AS FINL_ORAL_REQ_CD, ...
FROM YourTable T
INNER JOIN Constants C1 ON C1.ID = T.CPHIL_AWD_CD
INNER JOIN Constants C2 ON C2.ID = T.FINL_ORAL_REQ_CD

关于sql - 我需要为每个字段重写 case 语句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33883092/

相关文章:

sql - 使 OR 查询更加简化

c++ - 从 SQL Server 在 C++ native 客户端中返回 NULL 数据类型

sql-server - 如何检查表是否具有列存储索引?

mysql - 仅选择最近的日期

mysql - 如何排除使用 mysql 窗口函数创建的日期范围中的间隙?

sql - 查找一组查询使用了哪些表

sql - 带字符串的 TSQL 数据透视

sql - 在结果集末尾嵌入动态行

sql - 优化 SQL 距离查询

sql - 在 select 中添加 "-"而不是空格