SQL Pivot返回多个值

时间:2015-02-06 18:17:06

标签: pivot

这是问题所在。我有两个表,我目前在一个数据透视表中使用它来返回单个值,MAX(日期)。我被要求返回与该特定MAX(日期)相关的其他值。我知道我可以通过OVER PARTITION做到这一点,但它需要我做大约8或9个LEFT JOINS来获得所需的输出。我希望有办法让我现有的PIVOT返回这些值。更具体地说,让我们说每个MAX(日期)都有一个数据源,我们希望该特定源成为输出的一部分。以下是我所说的简单示例:

    Create table #Email
    (
        pk_id int not null identity primary key,
        email_address varchar(50),
        optin_flag bit default(0),
        unsub_flag bit default(0)
    )

Create table #History
    (
        pk_id int not null identity primary key,
        email_id int not null,
        Status_Cd char(2),
        Status_Ds varchar(20),
        Source_Cd char(3),
        Source_Desc varchar(20),
        Source_Dttm datetime
    )

Insert into #Email
Values
    ('test@test.com',1,0),
    ('blank@blank.com',1,1)

Insert into #History
values
    (1,'OP','OPT-IN','WB','WEB','1/2/2015 09:32:00'),
    (1,'OP','OPT-IN','WB','WEB','1/3/2015 10:15:00'),
    (1,'OP','OPT-IN','WB','WEB','1/4/2015 8:02:00'),
    (2,'OP','OPT-IN','WB','WEB','2/1/2015 07:22:00'),
    (2,'US','UNSUBSCRIBE','EM','EMAIL','3/2/2015 09:32:00'),
    (2,'US','UNSUBSCRIBE','ESP','SERVICE PROVIDER','3/2/2015 09:55:00'),
    (2,'US','UNSUBSCRIBE','WB','WEB','3/2/2015 10:15:00')

;with dates as 
    (
    select 
        email_id,
        [OP] as [OptIn_Dttm],
        [US] as [Unsub_Dttm]
    from 
        (
        select
            email_id,
            status_cd,
            source_dttm
        from #history
        ) as src
    pivot (min(source_dttm) for status_cd in ([OP],[US])) as piv
    )

select
    e.pk_id as email_id,
    e.email_address,
    e.optin_flag,
    /*WANT TO GET THE OPTIN SOURCE HERE*/ /*<-------------*/
    d.OptIn_Dttm,
    e.unsub_flag,
    d.Unsub_Dttm
    /*WANT TO GET THE UNSUB SOURCE HERE*/ /*<-------------*/
from #Email e
    left join dates d on e.pk_id = d.email_id

0 个答案:

没有答案