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

使用R语言sqldf包时遇near 'then'语法错误,求解决

问题排查与解决方案

错误根源

你的SQL语句中**marri_1字段的处理部分缺少case when关键字**,导致语法结构不完整,触发了"near 'then': syntax error"错误。具体错误行:

, marri_1 in (1, 2) then marri_1 --1:기혼, 2:이혼
     end as marri_1

这一行没有以case when开头,不符合SQL的CASE表达式语法规范。

修正后的完整SQL代码

project=sqldf('select distinct
              ID
              , sex  
              , case when age<30 then "1" --20대
                     when age<40 then "2" --30대
                     when age<50 then "3" --40대
                     when age<60 then "4" --50대
                     when age<70 then "5" --60대
                     when 70<=age then "6" --70대 
                     end as age_group  -- 建议修改别名,避免与原age字段重名
              , ho_incm
              , town_t
              , case when tins in (10, 20) then "1" --국민건강보험
                   when tins=30 then "2" --의료급여
                   end as tins_type  -- 同样建议修改别名
              , edu 
              , case when marri_1 in (1, 2) then marri_1 --1:기혼, 2:이혼
                   end as marri_1
              , case when EC1_1 in (1, 2) then EC1_1 --1:취업, 2:실업
                   end as EC1_1
              , case when BS3_1 in (1, 2) then "1" --현재흡연
                     when BS3_1=3 then "2" --과거흡연
                     when BS3_1=8 then "3" --비흡연
                     end as BS3_1_status  -- 修改别名避免重名
              , case when BD1_11 in (1, 2) then "2" --비음주
                     when BD1_11 in (3, 4, 5, 6) then "1" --음주
                     end as BD1_11_status  -- 修改别名
              , case when BP1 in (1, 2) then "1" --스트레스 많이느낌
                     when BP1 in (3, 4) then "2" --스트레스 적게느낌
                     end as BP1_status  -- 修改别名
              , case when HE_BMI<18.5 then "1" --저체중
                     when 18.5<=HE_BMI<23 then "2" --정상
                     when 23<=HE_BMI<25 then "3" --과체중
                     when 25<=HE_BMI then "4" --비만
                     end as BMI_category  -- 修改别名
              , case when DL1_dg in (0, 1) then DL1_dg --0:무, 1:유
                     end as DL1_dg
FROM data
WHERE age >= 19  -- 统一字段大小写,与select中的age保持一致
')

额外优化建议

  • 避免字段重名:原代码中多个CASE表达式的别名与原字段名相同(如age、tins等),虽然sqldf可能允许,但会降低代码可读性,建议修改为更具描述性的别名(如age_group、tins_type)。
  • 统一字段大小写:WHERE子句中的AGE与SELECT中的age保持一致,避免因数据库大小写敏感导致的问题。
  • 补充ELSE分支:部分CASE表达式没有ELSE分支,当字段值不满足所有WHEN条件时会返回NULL。如果需要处理这种情况,可以添加else '0'或其他默认值,例如:
    case when tins in (10, 20) then "1"
         when tins=30 then "2"
         else "0" -- 其他보험종류
         end as tins_type
    

内容的提问来源于stack exchange,提问作者박소이

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:25:22