Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 基于单列给定错误的多列透视_Sql_Sql Server - Fatal编程技术网

Sql 基于单列给定错误的多列透视

Sql 基于单列给定错误的多列透视,sql,sql-server,Sql,Sql Server,伙计们,我遇到了一个问题,我试图在同一列的基础上以两列为轴心。 在下面的示例中,我希望根据code值透视列ProductExternalFullName和Coverage这两个列。然而 sql server不允许我这样做。这方面有什么办法吗 问题的另一部分是我不能在子查询中包含grain(候选键)。如果我有候选关键点,枢轴将无法正常工作。 如果我能做到这一点,我可以用几种方法解决这个问题 此操作的脚本: IF (object_id('TblPivot','U') > 0) DROP TA

伙计们,我遇到了一个问题,我试图在同一列的基础上以两列为轴心。 在下面的示例中,我希望根据
code
值透视列
ProductExternalFullName
Coverage
这两个列。然而 sql server不允许我这样做。这方面有什么办法吗

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

此操作的脚本:

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不允许我基于一列的值在两列上进行透视

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

如果您的问题中没有显示您的查询,我们如何帮助您呢?@Gordon Linoff Done对于初学者,您的查询包括DependentRelationshipTypeName,您提供的示例表中没有该名称。这列是什么?它的别名是Relationship,所以可以假设这两个是相同的。