基于单列给出错误,在多列上进行数据透视

时间:2017-06-13 19:52:14

标签: sql sql-server

伙计我遇到了一个问题,我试图根据同一列调整2列。 在下面的示例中,我希望将基于ProductExternalFullName值的列CoverageCode进行透视。然而 sql server不会让我这样做。有没有解决这个问题?

问题的另一部分是我不能在子查询中包含grain(候选键)。如果我有候选键,则枢轴无法正常工作。 如果我能够做到这一点,我可以通过几种方式解决这个问题。

enter image description here

脚本:

IF (object_id('TblPivot','U') > 0)
DROP TABLE TblPivot

CREATE TABLE TblPivot
(
    ApplicationConsumerID int,
    Relationship varchar(25),
    Code varchar(100),
    ProductExternalFullName varchar(50),
    Coverage varchar(50)
)

GO

INSERT INTO TblPivot(ApplicationConsumerID, Relationship, Code, ProductExternalFullName, Coverage) VALUES
  (5730, 'Employee', 'MED1', 'Medical Plan1', 'Emp Only')
, (5730, 'Employee', 'DEN1', 'Dental Low Plan1', 'Emp Only')
, (5730, 'Employee', 'IDT1', 'Identity Theft Protection Plan1', 'Emp+Family')

我的尝试: 问题是Sql Server不会让我根据一列的值

来转向2列
select *
 from 
(   SELECT 
    de.ApplicationConsumerID,
    CASE WHEN RelationShip = 'Not Found' THEN 'Employee' ELSE DependentRelationshipTypeName END AS Relationship


     ,CASE WHEN DependentRelationshipTypeName = 'Not Found' THEN Code ELSE NULL END as Code
    ,CASE WHEN DependentRelationshipTypeName = 'Not Found' THEN ProductExternalFullName ELSE NULL END as ProductExternalFullName
    ,CASE WHEN DependentRelationshipTypeName = 'Not Found' THEN  CoverageTierNameELSE NULL END as CoverageTierName
    FROM        
    TblPivot
) as  a
PIVOT (MAX(a.ProductExternalFullName) FOR a.CODE IN (DEN, IDT, MED)) as pvt
PIVOT (MAX(a.CoverageTierName) FOR a.CODE IN (DEN, IDT, MED)) as pvt

0 个答案:

没有答案