SQL Select Distinct但包含分隔值

时间:2013-08-15 08:56:40

标签: sql sql-server sql-server-2008 asp-classic

来自表车辆的示例数据

ID     BODY TYPE        Litre
1      AAA              1.5
2      BBB; CCC         1.9
3      DDD              1.9
4      EEE; FFF; GGG    1.8
5      GGG              1.8

我需要一个Select Distinct语句,它会将以下结果带入查询中,因此我们选择所有唯一值,但也要分割;同样。

BODY TYPE
AAA
BBB
CCC
DDD
EEE
FFF
GGG

我查看了包含各种功能的类似问题,但我希望结果可以作为查询查看。我尝试将下面的建议改编为我的方案

2 个答案:

答案 0 :(得分:5)

试试这个 -

DECLARE @temp TABLE (string VARCHAR(50))

INSERT INTO @temp (string)
VALUES 
('AAA'),          
('BBB; CCC'),     
('DDD'),           
('EEE; FFF; GGG'), 
('GGG')    

SELECT DISTINCT LTRIM(t.c.value('.', 'VARCHAR(10)'))
FROM (
    SELECT ID = CAST ('<t>' + REPLACE(string, ';', '</t><t>') + '</t>' AS XML)
    FROM @temp
) r 
CROSS APPLY ID.nodes ('/t') t(c)

输出 -

----------
AAA
BBB
CCC
DDD
EEE
FFF
GGG

答案 1 :(得分:5)

您应该以规范化的形式存储数据。那说,试试这个

;with c as (
    select bodytype, 0 as start, CHARINDEX(';', bodytype) as sep 
    from Vehicle
    where litre=1.9 
    union all
    select bodytype, sep, CHARINDEX(';', bodytype, sep+1) from c
    where sep>0

)
    select distinct LTRIM(RTRIM(SUBSTRING(bodytype,start+1,chars))) as [BodyType]
    from
    (
        select *, Case sep when 0 then LEN(bodytype) else sep-start-1 end as chars
        from c
    ) v