使用基于3个字段的条件连接2个视图

时间:2015-02-11 11:02:17

标签: sql sql-server join null tableau

在SQL Server 2012中编写一个查询以加入这两个视图 - 广告系列和服务。 考虑这个条件

所有回复跟踪都需要在BP,移动和电子邮件ID级别上完成。

如果BP为null,则为Mobilenumber或emailid 或者如果手机号码为空,则采用BP或emailid 或者如果电子邮件ID为空,则采用Mobilenumber或BP。

将所有3个参数放在一起&不管是否填写了其他2个字段,将将3个密钥中的每个字段与相应的服务报告&最终结果是3个键的结果的OR。

我开始这样,但它不完整,没有意义。

select * from [dbo].[Campaign] left outer join 
              [dbo].[Services] on [Campaign].[Email]=[Services].[Email]
where [dbo].[Campaign].[Email] is not null and [dbo].[Campaign].[Mobile]is not null

屏幕截图显示了两个视图的所有字段

enter image description here

谢谢, 和Manish

2 个答案:

答案 0 :(得分:0)

您可以尝试这样做,(尝试理解背后的想法,以便您可以根据需要进行完全修改。

SELECT *
FROM [dbo].[Campaign]
LEFT OUTER JOIN [dbo].[Services] ON (
        ([Campaign].[Email] = [Services].[Email])
        OR ([Campaign].[Mobile] = [Services].[Mobile])
        )
WHERE [dbo].[Campaign].[bp] IS NULL

UNION ALL

SELECT *
FROM [dbo].[Campaign]
LEFT OUTER JOIN [dbo].[Services] ON (
        ([Campaign].[Email] = [Services].[Email])
        OR ([Campaign].[bp] = [Services].[bp])
        )
WHERE [dbo].[Campaign].[Mobile] IS NULL

UNION ALL

SELECT *
FROM [dbo].[Campaign]
LEFT OUTER JOIN [dbo].[Services] ON (
        ([Campaign].[Mobile] = [Services].[Mobile])
        OR ([Campaign].[bp] = [Services].[bp])
        )
WHERE [dbo].[Campaign].Email] IS NULL

答案 1 :(得分:0)

试试这个

SELECT *
FROM   [dbo].[Campaign] c
       LEFT OUTER JOIN [dbo].[Services] s
                    ON CASE
                         WHEN c.bp IS NULL
                              AND ( c.email = s.email
                                     OR c.mobile = s.mobile ) THEN 1
                         WHEN c.Mobile IS NULL
                              AND ( c.email = s.email
                                     OR c.bp = s.bp ) THEN 1
                         WHEN c.email IS NULL
                              AND ( c.bp = s.bp
                                     OR c.mobile = s.mobile ) THEN 1
                         ELSE 0
                       END = 1
WHERE  [dbo].[Campaign].[Email] IS NOT NULL
       AND [dbo].[Campaign].[Mobile]IS NOT NULL