SQL Pivot表困境

时间:2015-08-31 17:34:15

标签: sql join pivot pivot-table

我坚持写一个数据透视表。我有一个问题,因为我的一般查询需要是半复杂的。我们想要包含一堆刚刚转动的列。

 select distinct 
 a.customer_no,
 a.fname, 
 isnull(a.mname,'') as 'mname', 
 a.lname,  
 d.description,
 c.address
 from T_CUSTOMER a
 left outer join T_EADDRESS c on a.customer_no = c.customer_no
 join TR_EADDRESS_TYPE d on c.eaddress_type = d.id
 left outer join lt_nyo_applicants_cust_screen i on a.customer_no = i.customer_no
 where a.customer_no in (
                        Select Distinct a.customer_no 
                         From V_CUSTOMER_WITH_PRIMARY_GROUP a  WITH (NOLOCK)
                         Where  IsNull(a.inactive, 1) = 1 
                         AND EXISTS (select * from tx_cust_keyword WITH (NOLOCK) where tx_cust_keyword.customer_no in (select  customer_no from V_CUSTOMER_WITH_PRIMARY_GROUP where customer_no = a.customer_no) and tx_cust_keyword.key_value in ('Participant') And tx_cust_keyword.keyword_no = 651) 
                        UNION
                        Select Distinct a.customer_no 
                         From V_CUSTOMER_WITH_PRIMARY_GROUP a  WITH (NOLOCK)
                         JOIN (Select a1.customer_no From lt_nyo_applicants_cust_screen a1 WITH (NOLOCK) Where a1.application_status in (1) and a1.season in ('2014-2015','2015-2016')) as e ON e.customer_no = a.customer_no
                         Where  IsNull(a.inactive, 1) = 1 
                        )
and c.inactive = 'N'
order by customer_no

数据如下:

CUSTOMER_NO fnmame MNAME L-NAME 然后我们有一个描述字段(email_type),我们需要在其上进行透视 和电子邮件地址

customer_no fname   mname   lname   description             address         
5           john            Smith   Primary Email Address   js@gmail.com    
5           john            Smith   Secondary Email Address js@hotmail.com  
8           Joseph          Petty   Primary Email Address   jp2@gmail.com   

我想看到什么

customer_no fname   mname   lname    Primary Email Address Secondary Email Address 
5           john            Smith    js@gmail.com           js@hotmail.com   
8           Joseph          Petty    jp2@gmail.com  

1 个答案:

答案 0 :(得分:0)

像这样的东西

:with cte 
as
(
select distinct 
 a.customer_no,
 a.fname, 
 isnull(a.mname,'') as 'mname', 
 a.lname,  
 d.description,
...
)
select Customer_no,fname,mname,lname
       max(case when description = 'Primary Email Address' then address END) as [Primary Email Address],
       max(case when description = 'Secondary Email Address' then address END) as [Secondary Email Address]
from CTE
Group by Customer_no,fname,mname,lname