【问题标题】:SQL Pivot table dilemmaSQL 数据透视表困境
【发布时间】:2015-08-31 17:34:15
【问题描述】:

我一直在编写数据透视表。我遇到了一些问题,因为我的一般查询需要是半复杂的。我们想要包含一堆刚刚旋转的列。

 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 名字 名字 名字 然后我们有一个描述字段(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  

【问题讨论】:

    标签: sql join pivot pivot-table


    【解决方案1】:

    类似的东西

    :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
    

    【讨论】:

    • 如果我在最初的问题中不清楚,我深表歉意 - 问题是我有大约 6 种(但最多 10 种)类型的电子邮件地址,我想提取所有这些地址。如何在不为每种电子地址类型输入 case/max 语句的情况下执行此操作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    相关资源
    最近更新 更多