sql - 带有 CASE 语句的内部连接在 SQL SERVER 中不起作用

标签 sql sql-server tsql

我有两个,帐户代码如下,

table 1:

account  

50000
50006
50015
50105
50150
50155
50165

table 2:

Account

50000
50010
50140
50105
50150
50155
50165

我需要加入这两个。如果 table-1 的任何帐户代码与 table-2 不匹配,那么我已将 table-1 帐户代码隐式更改为 table-2 帐户代码。

我做了如下的事情,

 SELECT T1.Account, T2.Account
 FROM table1 t1 
 INNER JOIN table2 t2
 on (t2.account =  CASE t1 .account 
                   WHEN 50015 THEN 50010
                   WHEN 50006 THEN 50140
                   ELSE  t1 .account 
                    END )

但我只得到匹配的代码作为输出,

account Account
50000   50000
50105   50105
50150   50150
50155   50155
50165   50165

我没有得到不匹配的帐户代码,即 (50006 和 50015)。谁能帮我找出这里出了什么问题?

我的预期输出是

account Account
50000   50000
50006   50140
50015   50010
50105   50105
50150   50150
50155   50155
50165   50165

感谢帮助

最佳答案

使用 CASE 然后使用 DISTINCT 数据,这将为您提供通用解决方案

-- table1
declare  @table1 table
(account  bigint)

insert into @table1 values (50000)
insert into @table1 values (50006)
insert into @table1 values (50015)
insert into @table1 values (50105)
insert into @table1 values (50150)
insert into @table1 values (50155)
insert into @table1 values (50165)

-- table2
declare  @table2 table
(account  bigint)

insert into @table2 values (50000)
insert into @table2 values (50010)
insert into @table2 values (50140)
insert into @table2 values (50105)
insert into @table2 values (50150)
insert into @table2 values (50155)
insert into @table2 values (50165)


-- QUERY
select distinct t1.account as Account1, 
Account2 = case 
    when  t1.account = t2.account then t2.account else  t1.account
    end
from @table1 t1, @table2 t2

结果

Account1    Account2
50000       50000
50006       50006
50015       50015
50105       50105
50150       50150
50155       50155
50165       50165
评论后

编辑 - 这是我们要求的一部分。我需要更新50140中50006账号对应的金额等等...

select distinct t1.account as Account1, 
Account2 = case 
    when  t1.account = 50006 then 50140
    when  t1.account = 50015 then 50010 
    else  t1.account end
from @table1 t1 , @table2 t2

结果

Account1    Account2
50000       50000
50006       50140
50015       50010
50105       50105
50150       50150
50155       50155
50165       50165

关于sql - 带有 CASE 语句的内部连接在 SQL SERVER 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35285013/

相关文章:

sql - SQL 中的 NOT `column` IN (...) 与 `column` NOT IN (...)

c# - 使用单个查询仅选择不匹配项(仅限连接)

sql - 是否可以设置一个触发器,该触发器仅在特定列值更改时触发,并且取决于它调用不同函数的值是什么?

sql-server - FreeTDS:用户登录失败

sql - 闭表 根节点 数十百万节点查询性能

c# - Asp 网络核心 : Connection to existing SqlServer

sql - 在 SQL Server 中将 XML UTF-8 编码的字符串转换为 XML 数据类型

SQL Unpivot/Coalesce 多列基于值的一列

mysql - 真的很难理解这个查询

jquery - Rails-Jquery : Updating a Database Field on a click event