在SQL Server中执行嵌套case语句逻辑的最佳方法 [英] Best way to do nested case statement logic in SQL Server

查看:146
本文介绍了在SQL Server中执行嵌套case语句逻辑的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个SQL查询,其中需要根据相当多的条件来计算返回的一些列.

I'm writing an SQL Query, where a few of the columns returned need to be calculated depending on quite a lot of conditions.

我目前正在使用嵌套的case语句,但是它变得凌乱.有没有更好(更有条理和/或更易读)的方法?

I'm currently using nested case statements, but its getting messy. Is there a better (more organised and/or readable) way?

(我正在使用Microsoft SQL Server,2005)

(I am using Microsoft SQL Server, 2005)

一个简化的示例:

SELECT
    col1,
    col2,
    col3,
    CASE
        WHEN condition 
        THEN
            CASE
                WHEN condition1 
                THEN
                    CASE 
                        WHEN condition2
                        THEN calculation1
                        ELSE calculation2
                    END
                ELSE
                    CASE 
                        WHEN condition2
                        THEN calculation3
                        ELSE calculation4
                    END
            END
        ELSE 
            CASE 
                WHEN condition1 
                THEN 
                    CASE
                        WHEN condition2 
                        THEN calculation5
                        ELSE calculation6
                    END
                ELSE
                    CASE
                        WHEN condition2 
                        THEN calculation7
                        ELSE calculation8
                    END
            END            
    END AS 'calculatedcol1',
    col4,
    col5 -- etc
FROM table

推荐答案

您可以尝试某种COALESCE技巧,例如:

You could try some sort of COALESCE trick, eg:


SELECT COALESCE(
  CASE WHEN condition1 THEN calculation1 ELSE NULL END,
  CASE WHEN condition2 THEN calculation2 ELSE NULL END,
  etc...
)

这篇关于在SQL Server中执行嵌套case语句逻辑的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆