在另一个字段中创建字段关闭案例声明

时间:2016-10-14 14:25:28

标签: sql sql-server-2012 case-statement

我正在尝试找出一个可以帮助我根据我提取的源代码创建AgeBucket字段的查询。目前,我创建了一个名为BusinessAge的字段,它基本上计算了从给定请求的开始日期开始的工作日数,并尝试解释下面的代码。

CASE WHEN [EndDate] > [StartDate] THEN [BusinessCalendarDayNum] - [BusinessCalendarDayNum]  --End Date - Start Date
     WHEN [EndDate] IS NULL and [StartDate] IS NOT NULL THEN [BusinessCalendarDayNum] - [BusinessCalendarDayNum] -- GetDate - StartDate
     WHEN [EndDate] = [StartDate] THEN 1
     END AS BusinessAge,

根据它返回的数字,我想制作一个AgeBucket字段...例如说...

CASE WHEN BusinessAge >=0 and BusinessAge <6 THEN '0-5' 
     WHEN BusinessAge >5 and BusinessAge <11 THEN '6-10'  

等等,具有多种条件。

有没有办法操纵上面的查询并制作一个更复杂的多个case语句,我可以用它来创建Age Bucket字段?或者最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

尝试一些这样的想法

SELECT  BusinessAge ,
        CASE WHEN BusinessAge >= 0 AND BusinessAge < 6 THEN '0-5'
             WHEN BusinessAge >= 6 AND BusinessAge <11 THEN '6-10'
        END AS AgeBucket, 

FROM (
       SELECT CASE WHEN [EndDate] > [StartDate] THEN [BusinessCalendarDayNum] - [BusinessCalendarDayNum]  --End Date - Start Date
                   WHEN [EndDate] IS NULL and [StartDate] IS NOT NULL THEN [BusinessCalendarDayNum] - [BusinessCalendarDayNum] -- GetDate - StartDate
                   WHEN [EndDate] = [StartDate] THEN 1
              END AS BusinessAge
       FROM TableName
 )t  

更新:

SELECT CASE WHEN [EndDate] > [StartDate] THEN [BusinessCalendarDayNum] - [BusinessCalendarDayNum]  --End Date - Start Date
                   WHEN [EndDate] IS NULL and [StartDate] IS NOT NULL THEN [BusinessCalendarDayNum] - [BusinessCalendarDayNum] -- GetDate - StartDate
                   WHEN [EndDate] = [StartDate] THEN 1
              END AS BusinessAge,
       CASE WHEN 
                CASE WHEN [EndDate] > [StartDate] THEN [BusinessCalendarDayNum] - [BusinessCalendarDayNum]  --End Date - Start Date
                   WHEN [EndDate] IS NULL and [StartDate] IS NOT NULL THEN [BusinessCalendarDayNum] - [BusinessCalendarDayNum] -- GetDate - StartDate
                   WHEN [EndDate] = [StartDate] THEN 1
                END BETWEEN 0 AND 6 
            THEN '0-5'
            WHEN 
                CASE WHEN [EndDate] > [StartDate] THEN [BusinessCalendarDayNum] - [BusinessCalendarDayNum]  --End Date - Start Date
                   WHEN [EndDate] IS NULL and [StartDate] IS NOT NULL THEN [BusinessCalendarDayNum] - [BusinessCalendarDayNum] -- GetDate - StartDate
                   WHEN [EndDate] = [StartDate] THEN 1
                END BETWEEN 6 AND 11 
            THEN '6-11'
        END AS AgeBucket

FROM TableName