Hive case when thenTwo syntax structures:
-
Conditional judgmentfunctioncase A when B then C ,case and when are separated
Syntax: CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END
illustrate:If a is equal to b, then c is returned; if a is equal to d, then e is returned; otherwise, then f is returned.Note that there can be many conditions for judging when. For example, CASE 4 WHEN 5 THEN 5 WHEN 4 THEN 4 ELSE 3 END will return 4.
Example 1:
-
select case 100
-
when 50 then 'tom'
-
when 100 then 'mary'
-
else 'tim' end
-
from lxw_dual;
-
--mary
-
select case 200 when 50 then 'tom'when 100 then 'mary' else 'tim' end from lxw_dual;
-
--tim
-
This syntaxThe firstcase when it's together, used to process query results for a single column,Similar to if judgment
Syntax: CASE WHEN a THEN b [WHEN c THEN d]* [ELSE e] END
illustrate:If a is TRUE, it returns b; if c is TRUE, it returns d; otherwise, it returns eFor example: CASE WHEN 5>0 THEN 5 WHEN 4>0 THEN 4 ELSE 0 END will return 5; CASE WHEN 5<0 THEN 5 WHEN 4<0 THEN 4 ELSE 0 END will return 0.
Example 2:
-
select case when 1=2 then 'tom' when 2=2 then 'mary' else 'tim' end from lxw_dual;
-
--mary
-
select case when 1=1 then 'tom' when 2=2 then 'mary' else 'tim' end from lxw_dual;
-
--tom