【问题标题】:Updating sql table with results from left join (sql server)使用左连接的结果更新 sql 表(sql server)
【发布时间】:2014-11-18 00:15:46
【问题描述】:

我需要有关 SQL 服务器查询的帮助。我正在尝试根据将表与另一个外部源(表 2)左连接的结果来更新现有表(#Masterfile)。第 6 行基本上是一个标志,表明该 ID 是否存在于表 b 中。我是 sql 新手(几周前才开始学习),所以我的语法可能非常基础。我离开加入了#Masterfile 与新的感兴趣的表(表2),然后选择结果(并更新column6_flag)。

但是,我收到错误,将语句(a.column6_flag = case when x.column9 不为 NULL 然后 1 else 0 end)确定为罪魁祸首。任何帮助将非常感激!!!我尝试再次查看语法时的大小写,但无法确定它产生错误的原因。当我注释掉部分查询的情况时,它就起作用了。

再次感谢!

--Insert into #MasterFile 
 select distinct
     a.column1
     , a.column2
     , a.column3
     , a.column4
     , a.column5
     , a.column6_flag = case when x.column9 is not NULL  then 1 else 0 end
     , a.column7
     , x.column9
from 
    #Alldata a
left join 
    (select m.column9
     from #Masterfile m
     left join table2 n on m.id = n.id) x on a.id = x.id

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    仅将a.column6_flag 替换为column6_flag

    column6_flag = case when x.column9 is not NULL  then 1 else 0 end
    

    【讨论】:

      【解决方案2】:

      试试这个……

      SELECT DISTINCT column1,
                      column2,
                      column3,
                      column4,
                      column5,
                      column6_flag = CASE
                                       WHEN x.column9 IS NOT NULL THEN 1
                                       ELSE 0
                                     END,
                      column7,
                      x.column9
      FROM   #Alldata a
             LEFT JOIN (SELECT m.id,
                               m.column9
                        FROM   #Masterfile m
                               LEFT JOIN table2 n
                                      ON m.id = n.id) x
                    ON a.id = x.id 
      

      【讨论】:

        【解决方案3】:

        你只需要移动箱子,就像这样:

        select distinct
        a.column1
        , a.column2
        , a.column3
        , a.column4
        , a.column5
        , case when x.column9 is not NULL  then 1 else 0 end AS column6_flag
        , a.column7
        , x.column9
        from #Alldata a
        left join 
        (
        select 
        m.column9
        from #Masterfile m
        left join table2 n
        on m.id=n.id
        ) x
        on a.id=x.id
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-08-06
          • 2020-09-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多