Best way to do nested case statement logic in SQL Server

前端 未结 9 1402
误落风尘
误落风尘 2020-11-29 15:23

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

I\'m currently using nested case stateme

9条回答
  •  臣服心动
    2020-11-29 15:58

    Here's a simple solution to the nested "Complex" case statment: --Nested Case Complex Expression

    select  datediff(dd,Invdate,'2009/01/31')+1 as DaysOld, 
        case when datediff(dd,Invdate,'2009/01/31')+1 >150 then 6 else
            case when datediff(dd,Invdate,'2009/01/31')+1 >120 then 5 else 
                case when datediff(dd,Invdate,'2009/01/31')+1 >90 then 4 else 
                    case when datediff(dd,Invdate,'2009/01/31')+1 >60 then 3 else 
                        case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 2 else 
                            case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 1 end 
                        end
                    end
                end
            end
        end as Bucket
    from rm20090131atb
    

    Just make sure you have an end statement for every case statement

提交回复
热议问题