我很少在SQL中使用pivot,并且无法绕过它。我有查询,为医疗机构生成患者和保险的表格。我想返回一行,显示患者拥有的所有保险。
示例数据:
ID Insurance
1840 Medicaid Of New York
1841 Affinity Health Plan
1841 Medicaid Of New York
1842 Fidelis Care
1842 Medicaid Of New York
目标是显示如下数据:
我理解pivot的基本功能,但没有太多时间来弄清楚如何实现上述结果。我没有取得任何接近工作结果的东西,这可能是缺乏经验或疲劳。任何帮助将不胜感激。
答案 0 :(得分:2)
类似这样的事情
with data as (
select id,insurance ,row_number() over ( partition by id order by insurance) rowid
)
select d.id , [1] as ins1,[2] ins2,[3]ins3,[4] ins4
from data d
pivot
(max(insurance)
for rowid in ([1],[2],[3],[4])
)pv
答案 1 :(得分:2)
我更喜欢条件聚合:
SELECT ID,
MAX(CASE WHEN RN = 1 THEN INSURANCE ELSE '' END) AS INSURANCE1,
MAX(CASE WHEN RN = 2 THEN INSURANCE ELSE '' END) AS INSURANCE2,
MAX(CASE WHEN RN = 3 THEN INSURANCE ELSE '' END) AS INSURANCE3,
MAX(CASE WHEN RN = 4 THEN INSURANCE ELSE '' END) AS INSURANCE4
FROM (
SELECT ID,
INSURANCE,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY INSURANCE) RN
FROM YourTable
) A
GROUP BY ID
This可以很好地阅读条件聚合或交叉标签与PIVOT
答案 2 :(得分:1)
如果您最多有两个值(如示例数据和结果所示),则可以使用min()
和max()
:
select id,
min(insurance) as insurance1,
(case when min(insurance) <> max(insurance) then max(insurance)
end) as insurance2
from t
group by id;
答案 3 :(得分:0)
这是您正在寻找的。这将根据需要平整您的记录。
SELECT
ID, Insurance1, Insurance2, Insurance3, Insurance4
FROM ( SELECT
ID,
Insurance,
RN = 'Insurance' +
CAST(ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Insurance) AS CHAR(1))
FROM MyDB.MySchema.MyTable
) AS d
PIVOT(
MAX(Insurance)
for RN
in (Insurance1, Insurance2, Insurance3, Insurance4)
) AS p;