sqlÖÐcaseº¯ÊýµÄÓ÷¨
sql case º¯Êýͨ¹ý½ÏÁ¿±í´ïʽЧ¹ûÖ´Ðвî±ðµÄ²Ù×÷£¬ÆäÓ﷨Ϊ£ºwhen expression then result1when expression then result2…[else default_result]end
SQL ÖÐ CASE º¯ÊýµÄÓ÷¨
CASE º¯ÊýÔÚ SQL ÖÐÊÇÒ»¸öÇ¿Ê¢µÄ¹¤¾ß£¬ÓÃÓÚƾ֤±í´ïʽµÄЧ¹ûÖ´Ðвî±ðµÄ²Ù×÷¡£ÆäÓï·¨ÈçÏ£º
CASE WHEN expression1 THEN result1 WHEN expression2 THEN result2 ... [ELSE default_result] END
µÇ¼ºó¸´ÖÆ
Ó÷¨Ê¾Àý
ÀýÈ磬Ҫƾ֤Ա¹¤µÄ²¿·Ö»ñÈ¡ËûÃǵÄн³ê¹æÄ££¬¿ÉÒÔʹÓà CASE º¯Êý£º
SELECT salary, CASE department WHEN 'Sales' THEN '25,000 - 50,000' WHEN 'Engineering' THEN '35,000 - 75,000' WHEN 'Marketing' THEN '20,000 - 40,000' ELSE 'Unknown' END AS salary_range FROM employees;
µÇ¼ºó¸´ÖÆ
Õ⽫·µ»ØÒÔÏÂЧ¹û£º
н³ê | н³ê¹æÄ£ |
---|---|
30,000 | 25,000 – 50,000 |
50,000 | 35,000 – 75,000 |
25,000 | 20,000 – 40,000 |
ÆäËûÓÃÀý
CASE º¯ÊýÉÐÓÐÐí¶àÆäËûÓÃÀý£¬°üÀ¨£º
ÑéÖ¤Êý¾ÝÍêÕûÐÔ£ºÑéÖ¤Êý¾ÝÊÇ·ñÖª×ãijЩÌõ¼þ¡£
ת»»Êý¾ÝÃûÌ㺽«Êý¾Ý´ÓÒ»ÖÖÃûÌÃת»»ÎªÁíÒ»ÖÖÃûÌá£
¾ÛºÏÊý¾Ý£ºÆ¾Ö¤²î±ðÌõ¼þ¶ÔÊý¾Ý¾ÙÐзÖ×éºÍ»ã×Ü¡£
ÖØ´óÅÌÎÊ£ºÔÚÖØ´óµÄÅÌÎÊÖÐƾ֤²î±ðµÄÇéÐÎÖ´Ðвî±ðµÄ²Ù×÷¡£
×¢ÖØ£º
CASE Óï¾ä¿ÉÒÔ°üÀ¨¶à¸ö WHEN ×Ó¾äºÍÒ»¸ö ELSE ×Ӿ䣨¿ÉÑ¡£©¡£
ELSE ×Ó¾ä¿ÉÓÃÓÚÖ¸¶¨µ±ËùÓÐ WHEN ×Ӿ䶼²»Öª×ãʱµÄĬÈÏЧ¹û¡£
CASE Óï¾ä¿ÉÒÔǶÌ×£¬ÒÔ½¨Éè¸üΪÖØ´óµÄÌõ¼þ¡£
ÒÔÉϾÍÊÇsqlÖÐcaseº¯ÊýµÄÓ÷¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡