如何编写SQL查询按邮政编码拆分州?以马里兰分东西为例
Got it, here's how you can split Maryland into the two required regions while keeping all other states intact in your aggregation:
Solution SQL Query
SELECT CASE -- Handle Maryland's regional split WHEN State = 'Maryland' THEN CASE WHEN LEFT(CAST(zip AS VARCHAR), 3) IN ('216', '218', '219') THEN 'MD East' ELSE 'MD West' END -- Keep all other states as-is ELSE State END AS Region, SUM(Revenue) AS TotalRevenue FROM your_table_name GROUP BY CASE WHEN State = 'Maryland' THEN CASE WHEN LEFT(CAST(zip AS VARCHAR), 3) IN ('216', '218', '219') THEN 'MD East' ELSE 'MD West' END ELSE State END ORDER BY Region;
Key Details Explained
CASEStatement Logic: The outerCASEchecks if the row belongs to Maryland. If yes, the innerCASEevaluates the first 3 characters of the zip code to assign it to either MD East or MD West. All other states retain their original names.- Zip Code Handling:
CAST(zip AS VARCHAR)ensures we can safely use theLEFT()function even if yourzipfield is stored as a numeric type (likeINT). If yourzipis already a string column, you can simplify this toLEFT(zip, 3). - Group Consistency: The
GROUP BYclause mirrors the exactCASElogic from theSELECTstatement—this is critical to ensure the aggregation groups correctly by your new regional labels. - Result Count: This query will return 51 rows: 49 original states (excluding Maryland) plus MD East and MD West, which matches your requirement.
Quick Notes
- Double-check that the state name in your table matches
'Maryland'(case sensitivity depends on your database configuration). - Any Maryland zip codes not starting with 216, 218, or 219 will automatically fall into MD West, as requested.
内容的提问来源于stack exchange,提问作者brendensmall
相关产品推荐
相关产品推荐

