sqlÖÐcase whenÊÇʲôÒâ˼
case when Óï¾äÊÇÒ»ÖÖÌõ¼þÓï¾ä£¬ÓÃÓÚƾ֤Ìõ¼þÆÀ¹À¶à¸ö±í´ïʽ²¢·µ»Ø²î±ðÖµ¡£Ëü´ÓÉϵ½ÏÂÆÀ¹ÀÌõ¼þ£¬·µ»ØµÚÒ»¸öΪÕæµÄÌõ¼þ¶ÔÓ¦µÄÖµ£¬ÈôÊÇûÓÐÕæÌõ¼þ£¬Ôò·µ»ØĬÈÏÖµ£¨¿ÉÑ¡£©¡£
CASE WHEN Óï¾ä
½ç˵£º
SQL ÖÐµÄ CASE WHEN Óï¾äÊÇÒ»ÖÖÌõ¼þÓï¾ä£¬ÓÃÓÚƾ֤¸ø¶¨µÄÌõ¼þ½ÏÁ¿À´ÆÀ¹À¶à¸ö±í´ïʽ¡£ ËüÔÊÐíÎÒÃÇƾ֤²î±ðµÄÇéÐηµ»Ø²î±ðµÄÖµ¡£
Óï·¨£º
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE default_result END
µÇ¼ºó¸´ÖÆ
Ó÷¨£º
condition1, condition2, …£ºÒªÆÀ¹ÀµÄÌõ¼þ¡£
result1, result2, …£ºÈôÊÇÏìÓ¦µÄÌõ¼þΪÕ棬ÔòÒª·µ»ØµÄÖµ¡£
default_result£ºÈôÊÇËùÓÐÌõ¼þ¶¼Îª¼Ù£¬ÔòÒª·µ»ØµÄĬÈÏÖµ£¨¿ÉÑ¡£©¡£
ÊÂÇéÔÀí£º
CASE WHEN Óï¾ä´ÓÉϵ½ÏÂÆÀ¹ÀÌõ¼þ£¬Ö±µ½ÕÒµ½µÚÒ»¸öΪÕæµÄÌõ¼þ¡£ ÈôÊÇÕÒµ½ÁËÕæÌõ¼þ£¬Ôò·µ»ØÏìÓ¦µÄ result Öµ¡£ ÈôÊÇûÓÐÕæÌõ¼þ£¬Ôò·µ»Ø default_result Öµ£¨ÈôÊÇÒÑÖ¸¶¨£©¡£
ʾÀý£º
»ñȡѧÉúЧ¹ûÆ·¼¶£º
CASE WHEN grade >= 90 THEN 'A' WHEN grade >= 80 THEN 'B' WHEN grade >= 70 THEN 'C' WHEN grade >= 60 THEN 'D' ELSE 'F' END
µÇ¼ºó¸´ÖÆ
Óŵ㣺
¼ò»¯Ìõ¼þÂß¼£¬×èֹʹÓÃǶÌ×µÄ IF-ELSE Óï¾ä¡£
Ìá¸ß´úÂë¿É¶ÁÐԺͿÉά»¤ÐÔ¡£
×¢ÖØ£º
CASE WHEN Óï¾ä¿ÉÒÔ°üÀ¨¶à¸ö·ÖÖ§¡£
default_result ÊÇ¿ÉÑ¡µÄ£¬ÈôÊÇδָ¶¨£¬ÔòЧ¹û½«Îª NULL¡£
½ÏÁ¿Ìõ¼þʹÓà =¡¢>¡¢
ÒÔÉϾÍÊÇsqlÖÐcase whenÊÇʲôÒâ˼µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡