下面是我得到的结果,我应该得到的结果是排成一排。
AccountNumber Name UnitNumber AdmStatus AdmitDate Insurance1 Insurance2 Insurance3 Insurance4 Insurance5
V000123456 FERG M000123456 DIS IN 11/11/2019 ins1
V000123456 FERG M000123456 DIS IN 11/11/2019 ins2
但是我需要将结果与保险2排在一起
AccountNumber Name UnitNumber AdmStatus AdmitDate Insurance1 Insurance2 Insurance3 Insurance4 Insurance5
V000123456 FERG M000123456 DIS IN 11/11/2019 ins1 ins2
这是我所附的查询
SELECT AccountNumber
,CASE
WHEN bio.InsuranceOrderID = '1'
THEN bio.InsuranceID
ELSE ''
END AS 'Insurance1'
,CASE
WHEN bio.InsuranceOrderID = '2'
THEN bio.InsuranceID
ELSE ''
END AS 'Insurance2'
,CASE
WHEN bio.InsuranceOrderID = '3'
THEN bio.InsuranceID
ELSE ''
END AS 'Insurance3'
,CASE
WHEN bio.InsuranceOrderID = '4'
THEN bio.InsuranceID
ELSE ''
END AS 'Insurance4'
,CASE
WHEN bio.InsuranceOrderID = '5'
THEN bio.InsuranceID
ELSE ''
END AS 'Insurance5'
FROM BarVisits bv
LEFT OUTER JOIN BarInsuranceOrder bio ON bio.SourceID = bv.SourceID
AND bv.VisitID = bio.VisitID
WHERE AccountNumber = 'V000123456'
GROUP BY AccountNumber
,bio.InsuranceOrderID
,bio.InsuranceID
对列使用聚合函数并修复GROUP BY
:
SELECT AccountNumber,
MAX(case when bio.InsuranceOrderID ='1' then bio.InsuranceID ELSE '' END) AS Insurance1,
MAX(case when bio.InsuranceOrderID ='2' then bio.InsuranceID ELSE '' END AS Insurance2,
MAX(case when bio.InsuranceOrderID ='3' then bio.InsuranceID ELSE '' END AS Insurance3,
MAX(case when bio.InsuranceOrderID ='4' then bio.InsuranceID ELSE '' END) AS Insurance4
MAX(case when bio.InsuranceOrderID ='5' then bio.InsuranceID ELSE '' END) AS Insurance5
FROM BarVisits bv LEFT JOIN
BarInsuranceOrder bio
ON bio.SourceID = bv.SourceID AND bv.VisitID = bio.VisitID
WHERE AccountNumber = 'V000123456'
GROUP BY AccountNumber