2014-09-19 135 views
0

我在尝试对结果集进行非规范化,以便每个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> 

我研究了透视,但所有我看到的使用将不适用于聚合函数的例子。 我已经加入了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 

任何建议,将不胜感激。我真的很想找到一种方法来完成这个任务,而不需要有一块怪异的代码块(这是我在尝试完成时最终实现的)。谢谢!

回答

1

您可以使用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 

Sample SQL Fiddle

+1

甜!我非常接近 - 只是缺少MAX()函数。非常感谢;它做到了。 :) – rwking 2014-09-19 17:27:46