我试着去修饰一个结果集,这样我每个ID就有一个记录,这是多个共患病患者的列表。目前的数据如下:
ID Disease
1 Asthma
1 Cancer
1 Anemia
2 Asthma
2 HBP我需要它看起来像这样:
ID Disease1 Disease2 Disease3
1 Asthma Cancer Anemia
2 Asthma HBP <NULL or Blank>我研究了Pivot,但是我看到的所有例子都使用了不适用的聚合函数。我添加了row_number函数,并尝试了如下所示的自联接:
case when rownum = 1 then Disease else NULL end Disease1,
case when rownum = 2 then Disease else NULL end Disease2,
case when rownum = 3 then Disease else NULL end Disease3然而,这产生了以下情况:
ID Disease1 Disease2 Disease3
1 Asthma NULL NULL
1 NULL Cancer NULL
1 NULL NULL Anemia
2 Asthma NULL NULL
2 NULL HBP NULL如有任何建议,将不胜感激。我真的很想找到一种方法来完成这个任务,而不需要一个可怕的代码块(这就是我尝试这样做时得到的结果)。谢谢!
发布于 2014-09-19 17:23:15
您可以使用MAX压缩行:
select
id,
max(case when rownum = 1 then Disease end) Disease1,
max(case when rownum = 2 then Disease end) Disease2,
max(case when rownum = 3 then Disease end) Disease3
from (
select
id,
disease,
rownum = ROW_NUMBER() OVER (partition by id order by id)
from your_table
) sub
group by id示例SQL Fiddle
https://stackoverflow.com/questions/25939097
复制相似问题