如何从表中选择一组匹配值?

时间:2012-03-05 17:52:12

标签: sql sql-server

给出以下表结构:

create table SiteFeatures (
    Feature nvarchar(255),
    SiteUrl nvarchar(255)
)

以下示例数据:

Feature     SiteUrl
Feature1    /sites/a/
Feature1    /sites/a/l/
Feature2    /sites/a/l/
Feature3    /sites/a/l/
Feature4    /sites/a/l/rd/
Feature5    /sites/a/l/rd/
Feature6    /sites/a/l/rd/
Feature1    /sites/a/pa/
Feature2    /sites/a/pa/
Feature3    /sites/a/pa/
Feature4    /sites/a/pa/rd/
Feature5    /sites/a/pa/rd/
Feature6    /sites/a/pa/rd/
Feature4    /sites/a/s/rd/
Feature5    /sites/a/s/rd/
Feature6    /sites/a/s/rd/
Feature1    /sites/a/s/
Feature2    /sites/a/s/
Feature3    /sites/a/s/

我想检索每个唯一的功能组(最好是这些功能映射到的相应站点)。鉴于我想要返回的“分组”上面的示例数据将是:

Feature1
Feature1, Feature2, Feature3
Feature4, Feature5

如果有相应的网站,那么:

Feature1 = /sites/a/
Feature1,Feature2,Feature3 = /sites/a/l/, /sites/a/pa/, /sites/a/s/
Feature4,Feature5,Feature6 = /sites/a/l/rd/, /sites/a/pa/rd/, /sites/a/s/rd/

只要我返回了所需的组/关系,我就不太关心返回结果的格式。

是否可以在sql中执行此操作?

1 个答案:

答案 0 :(得分:1)

如果您使用的是SQL 2005或更高版本,则可以尝试:

select distinct
(
    STUFF 
    (
        (
            SELECT ',' + Feature
            FROM SiteFeatures t2
            WHERE  t1.SiteUrl = t2.SiteUrl
            ORDER BY Feature
            FOR XML PATH(''), TYPE, ROOT
        ).value('root[1]','nvarchar(max)')
        ,1,1,''
    )
) as chars
from SiteFeatures t1;