web123456

Two syntax structures of case when then in Hive

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:

  1. select case 100
  2.     when 50 then 'tom'
  3.     when 100 then 'mary'
  4.     else 'tim' end
  5. from lxw_dual;
  6. --mary
  7. select case 200 when 50 then 'tom'when 100 then 'mary' else 'tim' end from lxw_dual;
  8. --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:

  1. select case when 1=2 then 'tom' when 2=2 then 'mary' else 'tim' end from lxw_dual;
  2. --mary
  3. select case when 1=1 then 'tom' when 2=2 then 'mary' else 'tim' end from lxw_dual;
  4. --tom