sqlÖÐcasewhenµÄÓ÷¨
case when Óï¾äÓÃÓÚƾ֤Ìõ¼þ·µ»Ø²î±ðµÄÖµ£¬ÆäÓ÷¨°ì·¨Îª£ºÖ¸¶¨Ìõ¼þ£ºÈ·¶¨ÒªÆÀ¹ÀµÄÌõ¼þ¡£Ö¸¶¨Ð§¹û£ºÈôÊÇÌõ¼þΪ true£¬Ôò·µ»ØµÄÖµ¡£Ö¸¶¨ else ×Ӿ䣺ÈôÊÇûÓÐÌõ¼þΪ true£¬Ôò·µ»ØĬÈÏÖµ£¨¿ÉÑ¡£©¡£
SQL ÖÐ CASE WHEN Óï¾äµÄÓ÷¨
CASE WHEN Óï¾äÊÇÒ»ÖÖ SQL ÅÌÎÊÓïÑÔÖеÄÌõ¼þÐÔ±í´ïʽ£¬ÓÃÓÚƾָ֤¶¨µÄÌõ¼þ·µ»Ø²î±ðµÄÖµ¡£ÆäÓï·¨ÈçÏ£º
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE default_result END
µÇ¼ºó¸´ÖÆ
Ó÷¨°ì·¨£º
Ö¸¶¨Ìõ¼þ (condition)£ºÈ·¶¨ÒªÆÀ¹ÀµÄÌõ¼þ¡£
Ö¸¶¨Ð§¹û (result)£ºÈôÊÇÌõ¼þΪ true£¬Ôò·µ»ØµÄÖµ¡£
Ö¸¶¨ ELSE ×Ӿ䣺ÈôÊÇûÓÐÌõ¼þΪ true£¬Ôò·µ»ØĬÈÏÖµ£¨¿ÉÑ¡£©¡£
ʾÀý£º
SELECT CASE WHEN age > 18 THEN '³ÉÄê' WHEN age >= 13 AND age <p><strong>Ч¹û£º</strong></p>
µÇ¼ºó¸´ÖÆ
ѧÉúID | ÐÕÃû | ÄêËê | ÄêËêÖÖ±ð |
---|---|---|---|
1 | John | 20 | ³ÉÄê |
2 | Mary | 16 | ÇàÉÙÄê |
3 | Peter | 10 | ¶ùͯ |
ÆäËûÓ÷¨£º
·µ»Ø NULL Öµ£º¿ÉÒÔ½« ELSE ×Ó¾äÉèÖÃΪ NULL£¬ÒÔÔÚûÓÐÌõ¼þΪ true ʱ·µ»Ø¿ÕÖµ¡£
ǶÌ× CASE WHEN Óï¾ä£º¿ÉÒÔǶÌ× CASE WHEN Óï¾ä£¬ÒÔ´¦Àí¸üÖØ´óµÄÌõ¼þ¡£
ʹÓà CASE ±í´ïʽ×÷ΪɸѡÌõ¼þ£º¿ÉÒÔÔÚ WHERE ×Ó¾äÖÐʹÓà CASE ±í´ïʽÀ´É¸Ñ¡Êý¾Ý¡£
Óŵ㣺
¼ò»¯ÖØ´óÌõ¼þµÄÅÌÎÊ¡£
Ìá¸ßÅÌÎʵÄÐÔÄÜ£¬ÓÉÓÚЧÀÍÆ÷ÎÞÐèÖ´Ðжà¸ö IF-THEN Óï¾ä¡£
ÌṩһÖÖÔÚ SQL ÅÌÎÊÖд¦Àí²î±ðÇéÐεľ«Á··½·¨¡£
ÒÔÉϾÍÊÇsqlÖÐcasewhenµÄÓ÷¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡