数据透视表输出的SQL查询语法

时间:2014-03-17 21:13:37

标签: sql sql-server

我有一个表名 PatientInsurance ,它有两列Priority和PlanName。

有些患者有一种以上的保险而有些患者没有。

我通过加入患者表和 PatientInsurance 表来获取一些记录。

    From PatientInsurance Table :- Sample set of record for a specific patient.

    Priority      PlanName
    1             ADVANCE
    2             LOYALTY



Case when PatientInsurance.Priority = 1 , then output.PrimaryInsurance = PlanName
Case when PatientInsurance.Priority =2 , then output.SecondaryInsurance  = PlanName

Expected output as 

    PatientName PrimaryInsurance   SecondaryInsurance
     John        Advance             Loyalty
     Asif        BCBS 
     Merin       Advance              BCBS

如何编写查询以在单行输出中显示记录?

添加了一个sqlfiddle,请

http://sqlfiddle.com/#!3/57d47/2

2 个答案:

答案 0 :(得分:2)

您不需要枢轴,您可以使用子查询。您没有指定确切的架构,但它可能是:

select PatientName,
     (select PlanName from PatientInsurance
          where PatientInsurance.PatientId = Patient.PatientId
          and PatientInsurance.Priority = 1) as PrimaryInsurance,
     (select PlanName from PatientInsurance
          where PatientInsurance.PatientId = Patient.PatientId
          and PatientInsurance.Priority = 2) as SecondaryInsurance
from Patient

答案 1 :(得分:1)

您是否在寻找透视查询?

Select 
Pvt.PatientName, 
Pvt.[1] as PrimaryInsurance,
Pvt.[2] as SecondaryInsurance
From(
select P.PatientName , 
PIn.[Priority], 
PIn.PlanName
from Patient as P
inner join PatientInsurance as PIn
on P.Patid = Pin.PatId
) as normal  
PIVOT(
Max(PlanName)
For[Priority]
In([1],[2]) 
) as Pvt

它给了我你要求的输出。

相关问题