根据SQL Server中两个表的条​​件映射Null值

时间:2015-11-22 07:30:01

标签: sql sql-server sql-server-2008 tsql

想要映射两个表以显示如下数据:

表1“主要来源表”

╔════╦══════════╦═══════════╦════════════╗
║ ID ║ SourceID ║ ExternaID ║ SourceName ║
╠════╬══════════╬═══════════╬════════════╣
║  1 ║ NULL     ║ NULL      ║ AA         ║
║  2 ║ 4        ║ NULL      ║ BB         ║
║  3 ║ 5        ║ 1         ║ CC         ║
║  4 ║ 5        ║ 3         ║ DD         ║
╚════╩══════════╩═══════════╩════════════╝

表2“使用两个来源ID注册的客户信息”

╔════════╦══════════╦═══════════╗
║ custID ║ sourceID ║ ExternaID ║
╠════════╬══════════╬═══════════╣
║      4 ║        4 ║ NULL      ║
║      5 ║        5 ║ 1         ║
║      6 ║        5 ║ 1         ║
║      7 ║        5 ║ 3         ║
╚════════╩══════════╩═══════════╝
下面的

是所需的输出结果:

╔═══════════════════════════════════════╦══════════╦═══════════════════╦════════════╗
║ Total No. of Customers Per SourceName ║ SourceID ║ ExternalChannelID ║ SourceName ║
╠═══════════════════════════════════════╬══════════╬═══════════════════╬════════════╣
║                                     0 ║ NULL     ║ NULL              ║ AA         ║
║                                     2 ║ 5        ║ 1                 ║ CC         ║
║                                     1 ║ 5        ║ 3                 ║ DD         ║
║                                     1 ║ 4        ║ NULL              ║ BB         ║
╚═══════════════════════════════════════╩══════════╩═══════════════════╩════════════╝

所以这里为了找到客户使用的SourceName,我需要根据SourceID,ExternalID这两个列将它映射到主源表。 示例:如果客户具有SourceID = NULL AND ExternalID = NULL,那么它应该从主表中检查这两列并获取SourceName。 怎么做到这一点?

2 个答案:

答案 0 :(得分:2)

如果您的服务器支持is not distinct from

select count(*), t1.SourceName from table1 t1
join table2 t2 on t1.SourceId is not distinct from t2.SourceId
  and t1.ExternalId is not distinct from t2.ExternalId
group by t1.SourceName

select count(*), t1.SourceName from table1 t1
join table2 t2 on (t1.SourceId = t2.SourceId
  or (t1.SourceId is null and t2.SourceId is null))
  and (t1.ExternalId = t2.ExternalId
  or (t1.ExternalId is null and t2.ExternalId is null))
group by t1.SourceName

答案 1 :(得分:0)

使用相关子查询:

select *, 
      (select isnull(count(*), 0) from customertable c 
       where (c.sourceid = m.sourceid or (c.sourceid is null and m.sourceid is null)) and  
             (c.externalid = m.externalid or (c.externalid is null and m.externalid is null)) )
from mastertable m