SQL中的案例表达

时间:2017-08-24 18:14:16

标签: sql

我有一个简单的case表达式,它在下面的SQL服务器中运行。我期待看到结果超过12个HRS,超过25个HRS,超过45个HRS,等等。但是,我的结果仅返回12个HRS和12个HRS。请有人开导我。

谢谢, 乔

SELECT
STORE,
CASE
WHEN HOURS >12 THEN 'Over 12 HRS'
WHEN HOURS >25 THEN 'Over 25 HRS'
WHEN HOURS >45 THEN 'Over 45 HRS'
WHEN HOURS >55 THEN 'Over 55 HRS'
WHEN HOURS >75 THEN 'Over 75 HRS'
WHEN HOURS >94 THEN 'Over 94 HRS'
ELSE                'Less 12 HRS'
END                AS HOURS,
COUNT (ID)         AS PRD

FROM
(
    SELECT
    ID,
    STORE,
    HOURS
    FROM TABLE A
)X
GROUP BY STORE,
CASE
WHEN HOURS >12 THEN 'Over 12 HRS'
WHEN HOURS >25 THEN 'Over 25 HRS'
WHEN HOURS >45 THEN 'Over 45 HRS'
WHEN HOURS >55 THEN 'Over 55 HRS'
WHEN HOURS >75 THEN 'Over 75 HRS'
WHEN HOURS >94 THEN 'Over 94 HRS'
ELSE                'Less 12 HRS'
END 

3 个答案:

答案 0 :(得分:0)

这是因为您以错误的方式对案例进行了排序:当HOURS >94为真时,HOURS >12也必须为真,因此HOURS >94必须在HOURS >12之前。< / p>

一般来说,条件必须从强到弱排序,而不是相反。

以相反的方式重新排序列表将解决此问题:

CASE
WHEN HOURS >94 THEN 'Over 94 HRS'
WHEN HOURS >75 THEN 'Over 75 HRS'
WHEN HOURS >55 THEN 'Over 55 HRS'
WHEN HOURS >45 THEN 'Over 45 HRS'
WHEN HOURS >25 THEN 'Over 25 HRS'
WHEN HOURS >12 THEN 'Over 12 HRS'
ELSE                'Less 12 HRS'
END  AS HOURS

答案 1 :(得分:0)

case在第一个匹配的行停止,因此13个小时符合第一个条件,23个小时和75个小时等等。

你需要扭转逻辑。一种简单的方法是通过反转比较顺序:

(CASE WHEN HOURS <= 12 THEN 'Less 12 HRS'
      WHEN HOURS <= 25 THEN 'Over 12 HRS'
      WHEN HOURS <= 45 THEN 'Over 25 HRS'
      WHEN HOURS <= 55 THEN 'Over 45 HRS'
      WHEN HOURS <= 75 THEN 'Over 55 HRS'
      WHEN HOURS <= 94 THEN 'Over 75 HRS'
      ELSE 'Over 94 HRS'
 END) AS HOURS,

我还建议你重命名这些组。类似的东西:

(CASE WHEN HOURS <= 12 THEN '00-12 HRS'
      WHEN HOURS <= 25 THEN '12-25 HRS'
      WHEN HOURS <= 45 THEN '25-45 HRS'
      WHEN HOURS <= 55 THEN '45-55 HRS'
      WHEN HOURS <= 75 THEN '55-75 HRS'
      WHEN HOURS <= 94 THEN '75-94 HRS'
      ELSE '94+ HRS'
 END) AS HOURS,

答案 2 :(得分:0)

25,45,55,75和94都大于12.因此,第一个条件检查匹配,并且不需要进一步评估。你想这样写:

CASE
  WHEN HOURS >94 THEN 'Over 94 HRS'
  WHEN HOURS >75 THEN 'Over 75 HRS'
  WHEN HOURS >55 THEN 'Over 55 HRS'
  WHEN HOURS >45 THEN 'Over 45 HRS'
  WHEN HOURS >25 THEN 'Over 25 HRS'
  WHEN HOURS >12 THEN 'Over 12 HRS'
ELSE                  'Less 12 HRS'
END