在同一 SELECT 语句中对多个列重复使用 Case 语句
我有一个来自调查的大表,其中所有答案都是相似的,但我需要使它们保持一致。我需要对所有列重复使用相同的 case 语句,但这会导致非常难看且很长的查询。有没有办法将案例放入存储过程、UDF 或其他我可以更改被调用列的东西?
示例:
-- Example Case statement I need for all Columns
CASE
WHEN Happy IN ('Yes','True','Y','1') THEN 'Yes'
WHEN Happy IN ('No','False','N','0') THEN 'No'
WHEN Happy LIKE 'Don_t Know' or Happy IN ('Unknown','U','999','-1') THEN 'Unknown'
WHEN Happy IN ('Missing','Blank','-4') THEN 'Missing'
END AS HappyClean
-- Example table
SELECT Happy
,Sad
,DownBad
,FeelinGood
From Emotions
实际的列数超过 50,而 Case 实际上长了 2 行,因此您可以看到如果我必须为每列复制粘贴该代码,代码会有多长。顺便说一句,我正在使用 SQL Server。
感谢任何帮助!
I have a big table from a survey where all the answers are similar but I need to make them consistent. I need to reuse the same case statement for all the columns, however that would lead to a very ugly and long query. Is there a way to make a case into a stored procedure, UDF or something where I can just change the called column?
Examples:
-- Example Case statement I need for all Columns
CASE
WHEN Happy IN ('Yes','True','Y','1') THEN 'Yes'
WHEN Happy IN ('No','False','N','0') THEN 'No'
WHEN Happy LIKE 'Don_t Know' or Happy IN ('Unknown','U','999','-1') THEN 'Unknown'
WHEN Happy IN ('Missing','Blank','-4') THEN 'Missing'
END AS HappyClean
-- Example table
SELECT Happy
,Sad
,DownBad
,FeelinGood
From Emotions
The actual number of Columns is over 50 and the Case is actually 2 lines longer so you can see how long the code would be if I had to copy paste that code for every column. I am using SQL Server btw.
Appreciate any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建一个映射表,插入所有替换对一次,然后连接:
You can just create a mapping table, insert all the replacement pairs once, then join:
您还可以使用虚拟
VALUES
表You can also use a virtual
VALUES
table我可能会创建一个映射表,并在查询中使用左联接链接到它,以获取那些仍然与任何内容都不匹配的答案。
I might create a mapping table and link to it in the query using left joins for those answers that still don't match with anything.