带有布尔运算符的SQL CASE语句

时间:2017-07-28 07:47:10

标签: sql sql-server case

见声明:

SELECT      t1.region, 
            Count(t1.orders) AS orders, 
            CASE t1.week 
                      WHEN < '5' THEN 'APR' 
                      WHEN < '10' THEN 'MAY' 
                      WHEN < '14' THEN 'JUN' 
                      WHEN < '19' THEN 'JUL' 
                      WHEN < '23' THEN 'AUG' 
                      WHEN < '27' THEN 'SEP' 
                      WHEN < '32' THEN 'OCT' 
                      WHEN < '36' THEN 'NOV' 
                      WHEN < '40' THEN 'DEC' 
                      WHEN < '45' THEN 'JAN' 
                      WHEN < '49' THEN 'FEB' 
                      WHEN < '53' THEN 'MAR' 
            END AS month, 
            dbo.inf_dates.months

FROM        dbo.[NonVoice Weekly_InflowCOMCAN] AS t1 
INNER JOIN  dbo.inf_dates 
                ON t1.week = dbo.inf_dates.fin_wk

WHERE       notes = 'Weekly COMPLETED'
            AND ([2MB/sub]) = 'ETH' 
            AND dbo.inf_dates.date > CONVERT(datetime, '2017-04-03 00:00:00', 102)

GROUP BY   t1.region 
           ,dbo.inf_dates.months 

正如您所看到的那样,我正在尝试使用月份对行进行分组,而不是通过创建月份列并将周数组合在一起来对表格中的行进行分组。当我做CASE WHEN t1.Week < '5' THEN 'APR'这样的案例陈述时,我得到了正确的结果,但它迫使我按周分组,这不是我想要的。表中的两个月栏目顺便说一下。

1 个答案:

答案 0 :(得分:1)

这是正确的格式,同时将varchar<符号进行比较非常奇怪 也许你必须先把你的几周投入整数 顺便说一句,如果一周超过或等于53?

此外,您最好使用相应的表而不是对案例进行硬编码。

SELECT      t1.region, 
            Count(t1.orders) AS orders, 
            CASE 
                  WHEN t1.week < 5 THEN 'APR'
                  WHEN t1.week < 10 THEN 'MAY'
                  WHEN t1.week < 14 THEN 'JUN' 
                  WHEN t1.week < 19 THEN 'JUL' 
                  WHEN t1.week < 23 THEN 'AUG' 
                  WHEN t1.week < 27 THEN 'SEP' 
                  WHEN t1.week < 32 THEN 'OCT' 
                  WHEN t1.week < 36 THEN 'NOV' 
                  WHEN t1.week < 40 THEN 'DEC' 
                  WHEN t1.week < 45 THEN 'JAN' 
                  WHEN t1.week < 49 THEN 'FEB' 
                  WHEN t1.week < 53 THEN 'MAR' 
                  ELSE 'DEFAULT VALUE'
            END AS month, 
            dbo.inf_dates.months

FROM        dbo.[NonVoice Weekly_InflowCOMCAN] AS t1 
            INNER JOIN dbo.inf_dates 
                ON t1.week = dbo.inf_dates.fin_wk

WHERE       notes = 'Weekly COMPLETED'
            AND [2MB/sub]) = 'ETH' 
            AND dbo.inf_dates.date > CONVERT(datetime, '2017-04-03 00:00:00', 102)

GROUP BY   t1.region 
           ,dbo.inf_dates.months