-1

我有两个表,tb1(account, status) 和 tbl2(account status_ex)。例如

account    status
0001       A
0002       CD
0003       AB

account    status_ex
0001       78
0002       NULL
0003       9

我想写一个查询来组合两个状态列,结果表应该是这样的

account    status
0001       A78
0002       CD
0003       AB9

我尝试了以下查询

select tb1.account, 
  stuff(tbl1.status, len(tbl.status)+1, len(tbl.status), tb2.status_ex) as status
from tb1 left join tb2
on tbl.account=tb2.accont

但是结果不正确,我做错了什么?

4

2 回答 2

5
SELECT 
  tb1.account, 
  status = COALESCE(tb1.status, '') + COALESCE(tb2.status, '')
FROM tb1 INNER JOIN tb2 -- is LEFT JOIN right? Not sure.
ON tb1.account = tb2.account;
于 2012-09-24T19:49:29.297 回答
3

您可以使用IsNull()并仅连接这些值(请参阅SQL Fiddle with Demo):

select t1.account,
  isnull(t1.status, '') + isnull(t2.status_ex, '') status
from tb1 t1
inner join tb2 t2
  on t1.account = t2.account

您没有发布数据类型的内容,status_ex因此如果该status_ex字段是不同的数据类型,那么您将需要cast()它:

select t1.account,
  isnull(t1.status, '') 
    + isnull(cast(t2.status_ex as varchar(10)), '') status
from tb1 t1
inner join tb2 t2
  on t1.account = t2.account
于 2012-09-24T19:51:13.370 回答