我不确定如何说出来,但我希望根据条件将一列的值移动到另一行。
有些UnitNumbers只有一个InsuranceID,有些则有两个。
我想将第二个InsuranceID放在他们自己的列中,但与第一行保持在同一行。
我有这个:
SELECT v.UnitNumber, InsuranceOrderID, ord.InsuranceID
FROM Visits v
INNER JOIN BarInsuranceOrder ord
ON ord.VisitID=v.VisitID
返回此内容:
UnitNumber InsuranceOrderID InsuranceID
---------- ---------------- -----------
M7090226 1 UNITEDMCD
M2133443 1 MCR
M2133443 2 NEWERASUP
M2173835 1 MCRCAREIMP
M2173835 2 MCD
M2179062 1 MCD
M2165847 1 AMERIGROUP
但是我想要回复这样的事情:
UnitNumber InsuranceID SecondaryIns
---------- ----------- -----------
M7090226 UNITEDMCD
M2133443 MCR NEWERASUP
M2173835 MCRCAREIMP MCD
M2179062 MCD
M2165847 AMERIGROUP
据我所知,但我认为它没有朝着正确的方向前进:
SELECT v.UnitNumber
, (CASE WHEN InsuranceOrderID = '1' THEN ord.InsuranceID ELSE '-' END) [PrimaryIns]
, (CASE WHEN InsuranceOrderID = '2' THEN ord.InsuranceID ELSE '-' END) [SecondaryIns]
FROM Visits v
INNER JOIN BarInsuranceOrder ord
ON ord.VisitID=v.VisitID
UnitNumber InsuranceID SecondaryIns
---------- ----------- -----------
M7090226 UNITEDMCD -
M2133443 MCR -
M2133443 - NEWERASUP
M2173835 MCRCAREIMP -
M2173835 - MCD
M2179062 MCD -
M2165847 AMERIGROUP -
我对SQL很新,所以感谢任何帮助。
答案 0 :(得分:0)
你可以使用它。
SELECT UnitNumber, [1] InsuranceID, [2] SecondaryIns FROM
(
SELECT v.UnitNumber, InsuranceOrderID, ord.InsuranceID
FROM Visits v
INNER JOIN BarInsuranceOrder ord
ON ord.VisitID=v.VisitID
) SRC
PIVOT (MAX(InsuranceID) FOR InsuranceOrderID IN ([1],[2]) )PVT
结果
UnitNumber InsuranceID SecondaryIns
---------- ----------- ------------
M7090226 UNITEDMCD NULL
M2179062 MCD NULL
M2173835 MCRCAREIMP MCD
M2165847 AMERIGROUP NULL
M2133443 MCR NEWERASUP
答案 1 :(得分:0)
你非常接近。你只需要聚合:
SELECT v.UnitNumber,
MAX(CASE WHEN InsuranceOrderID = 1 THEN ord.InsuranceID END) as [PrimaryIns],
MAX(CASE WHEN InsuranceOrderID = 2 THEN ord.InsuranceID END) as [SecondaryIns]
FROM Visits v INNER JOIN
BarInsuranceOrder ord
ON ord.VisitID = v.VisitID
GROUP BY v.UnitNumber;
注意:
ELSE
。我认为NULL
足以开始 - 并且与您期望的结果更加一致。答案 2 :(得分:0)
加入自身并限制你想要的类型。
SELECT v.UnitNumber, InsuranceOrderID, PrimaryIns.InsuranceID,SecIns.InsuranceID
FROM Visits v
INNER JOIN BarInsuranceOrder PrimaryIns
ON ord.VisitID=v.VisitID and InsuranceOrderID =1
LEFT JOIN BarInsuranceOrder SecIns
ON ord.VisitID=v.VisitID and InsuranceOrderID =2