查询在Sql Server中连接两个表

时间:2014-11-28 12:30:25

标签: sql-server tsql sql-server-2012

我有两张桌子:

TABLE1 (currency nchar(3), seq int)
TABLE2 (code, currency nchar(3), seq int, value money)

TABLE1

的示例数据
currency    seq
USD          1
EUR          2
CNY          3
GBP          4

TABLE2

的示例数据
code     currency       seq    value
111       USD            1     650,90
111       AED            5     330,80

222       USD             1     540,90
222       GBP             4     778,40
222       EUR             2     290,30

现在,我需要添加TABLE2来自TABLE1的{​​{1}}种货币,但仅限于TABLE2中某些code缺少的货币。

示例输出:

   code    currency     seq    value
   111       USD         1     650,90
   111       AED         5     330,80      --this currency should stay even it is not in TABLE1
   111       EUR         2     NULL        --this currency was missing for code 111
   111       CNY         3     NULL        --this currency was missing for code 111
   111       GBP         4     NULL        --this currency was missing for code 111

   222       USD         1     540,90
   222       GBP         4     778,40
   222       EUR         2     290,30
   222       CNY         3     NULL       --this currency was missing for code 222

我可以展示我构建查询的尝试,但它们都失败了。

2 个答案:

答案 0 :(得分:0)

  Insert Into TABLE2 (currency,seq)
  select currency,seq from Table1 t1 where t1.currency  not in (select currency   from Table2)     

答案 1 :(得分:0)

尝试以下查询,看看是否有帮助:

insert into TABLE2 (code, currency, seq, value)
select t.GroupCode, t.currency, t.seq, NULL
from
(
    select t2.code as GroupCode, t1.currency, t1.seq
    from (select code, currency from TABLE2 group by code, currency) t2
    cross join TABLE1 t1 ) t
left join (select code, currency from TABLE2 group by code, currency) t3
on t.currency = t3.currency
where t3.code is null
group by t.GroupCode, t.currency, t.seq