SQL查询连接基于条件

时间:2012-08-31 01:04:55

标签: sql oracle

我想加入两个表“customer”和“activation”。以下是他们的结构:

 CUSTOMER                       Activation
 ------------                  ------------- 
 Id      Name                   EntityId       Date_Created       Type
 1       A                         1               2012            EMAIL
 2       B                         2               2011            SMS
 3       C

现在,我想在customer.Id = Activation.EntityId上加入这两个表。但是,我希望我的最终表格结构如下:

 Id    Name    Date_Email       Date_SMS       

 1      A        2012             NULL
 2      B        NULL             2011

基本上,Date_Email和Date_SMS列都来自Activation.Date_Created列。如果Activation.Type是EMAIL,我将最终结果中的Date_Email设置为Date_created,并将Date_SMS设置为null。如果Activation.type是SMS,我会以其他方式执行。

我现在拥有的是:

SELECT Customer.Id, Name, Date_Created AS Date_EMail, DATE_Created AS Date_SMS 
from Customer 
inner join Activation ON Customer.Id = Activation.EntityId;

现在,我需要根据Activation.Type列创建一个If-else条件。我对此很陌生,我无法通过谷歌搜索来解决这个问题。我正在使用Oracle XE数据库btw

有人可以帮我吗?感谢

2 个答案:

答案 0 :(得分:3)

SELECT Id, Name, A1.Date_Created as Date_Email, A2.Date_Created as Date_SMS FROM
CUSTOMER C
LEFT JOIN Activation A1 ON C.Id=A1.EntityID AND A1.Type='EMAIL'
LEFT JOIN Activation A2 ON C.Id=A2.EntityID AND A1.Type='SMS'

这也会添加ID = 3的实体,其中Date_EmailDate_SMS为空。我不知道Oracle的语法,你可以用WHERE NOT (IsNull(Date_Email) && IsNull(Date_SMS))

之类删除ID = 3

答案 1 :(得分:2)

你需要连接两次,每种类型一次(并使用LEFT JOIN来允许空值):

SELECT Customer.Id, Name, ActEmail.Date_Created AS Date_EMail, ActSMS.DATE_Created AS Date_SMS 
FROM Customer 
LEFT OUTER JOIN Activation AS ActEmail ON Customer.Id = ActEmail.EntityId AND ActEmail.Type = 'EMAIL'
LEFT OUTER JOIN Activation AS ActSMS ON Customer.Id = ActSMS.EntityId AND ActSMS.Type = 'SMS'