SQL Server:将文本行折叠为一行或多行

时间:2015-09-25 12:39:16

标签: sql-server select sql-server-2008-r2 hierarchy collapse

我正在尝试折叠维护层次结构的表。

我使用的是SQL Server 2008 R2。

数据看起来像这样。我很独特:

ID  Country City        District            Street          amount
------------------------------------------------------------------
1   USA     New York    NULL                NULL            1
1   USA     New York    Manhattan           NULL            1
2   EU      Paris       NULL                NULL            1
2   EU      Paris       arrondissement II   NULL            1
2   EU      Paris       arrondissement II   Rue Vivienne    1
2   EU      Paris       arrondissement IV   NULL            1
2   EU      Paris       arrondissement IV   Rue de Rivoli   1

到此:

ID  Country City      District          Street        amount
------------------------------------------------------------
1   USA     New York  Manhattan         NULL            1
2   EU      Paris     arrondissement II Rue Vivienne    1
2   EU      Paris     arrondissement IV Rue de Rivoli   1

示例代码:

create table DataTab
(
    ID  [varchar](10),
    Country [varchar](10),
    City [varchar](10),
    District [varchar](50),
    Street [varchar](50),
    amount [int]
);

Insert into DataTab
values (1, 'USA', 'New York', NULL, NULL, 1);

Insert into DataTab
values (1, 'USA', 'New York', 'Manhattan', NULL, 1);

Insert into DataTab
values (2, 'EU', 'Paris', NULL, NULL, 1);

Insert into DataTab
values (2, 'EU', 'Paris', 'arrondissement II', NULL, 1);

Insert into DataTab
values (2, 'EU', 'Paris', 'arrondissement II', 'Rue Vivienne', 1);

Insert into DataTab
values (2, 'EU', 'Paris', 'arrondissement IV', NULL, 1);

Insert into DataTab
values (2, 'EU', 'Paris', 'arrondissement IV', 'Rue de Rivoli', 1);

select * from DataTab;

我试图用CTE解决问题,但不知怎的,我找不到可行的解决方案。

希望你有时间提供帮助。

1 个答案:

答案 0 :(得分:2)

它可能不是解决此类问题的标准方法,但请尝试此查询:

SELECT ID
    ,Country
    ,City
    ,District
    ,Street
    ,amount
FROM (
    SELECT *
        ,max(score) OVER (PARTITION BY id) max_score
    FROM (
        SELECT *
            ,CASE WHEN Country IS NOT NULL THEN 1 ELSE 0 END + 
             CASE WHEN City IS NOT NULL THEN 1 ELSE 0 END + 
             CASE WHEN District IS NOT NULL THEN 1 ELSE 0 END + 
             CASE WHEN Street IS NOT NULL THEN 1 ELSE 0 END + 
             CASE WHEN amount IS NOT NULL THEN 1 ELSE 0 END score
        FROM DataTab
        ) result_set
    GROUP BY ID
        ,Country
        ,City
        ,District
        ,Street
        ,amount
        ,score
    ) result_set
WHERE score = max_score

您还可以找到示例SQLFiddle here