【问题标题】:Denormalizing result set非规范化结果集
【发布时间】:2014-09-20 01:23:15
【问题描述】:

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

任何建议将不胜感激。我真的很想找到一种方法来实现这一点,而无需使用大量代码(这是我在尝试这样做时最终得到的)。谢谢!

【问题讨论】:

    标签: sql-server-2008 denormalized


    【解决方案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

    【讨论】:

    • 甜蜜!我是如此接近 - 只是错过了 MAX() 函数。太感谢了;它成功了。 :)
    猜你喜欢
    • 2010-10-06
    • 2015-05-13
    • 2013-08-21
    • 2016-05-13
    • 2018-06-06
    • 2013-02-16
    • 2021-06-13
    • 2020-04-06
    • 2017-09-06
    相关资源
    最近更新 更多