SQL 服务器:将文本行折叠成一行或多行

SQL Server : collapse text rows into one or more rows

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

我正在使用 SQL Server 2008 R2。

数据看起来像这样。 ID 是唯一的:

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 解决问题,但不知何故我找不到可行的解决方案。

希望您有时间帮忙。

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

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