You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写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

  • CASE Statement Logic: The outer CASE checks if the row belongs to Maryland. If yes, the inner CASE evaluates 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 the LEFT() function even if your zip field is stored as a numeric type (like INT). If your zip is already a string column, you can simplify this to LEFT(zip, 3).
  • Group Consistency: The GROUP BY clause mirrors the exact CASE logic from the SELECT statement—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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 20:38:13