将不同的列值连接到字符串

时间:2012-12-03 12:22:24

标签: sql concatenation distinct

我想为字符串选择不同的列组合。我不知道如何在查询中执行此操作。该方案如下

c1   c2   c3
a     1    x
b     2    x
b     2    y

我想要一个像

这样的结果集
a:1:x
a:1:y
a:2:x
a:2:y
b:1:x
b:1:y
b:2:x
b:2:y

有关如何操作的任何建议吗?

3 个答案:

答案 0 :(得分:3)

示例CREATE TABLE语句

create table #Test( c1 char(1), c2 char(1), c3 char(1) )
insert INTO #Test
SELECT
    'a', '1', 'x'
UNION ALL SELECT
    'b', '2', 'x'
UNION ALL SELECT
    'b', '2', 'y'

所有不同列值的组合

select 
    c1List.c1, c2List.c2, c3List.c3
from ( 
    select DISTINCT c1 from #Test ) c1List
CROSS JOIN (
    select DISTINCT c2 from #Test ) c2List
CROSS JOIN (
    select DISTINCT c3 from #Test ) c3List

字符串连接

select 
    c1List.c1 + ':' + c2List.c2 + ':' + c3List.c3
from ( 
    select DISTINCT c1 from #Test ) c1List
CROSS JOIN (
    select DISTINCT c2 from #Test ) c2List
CROSS JOIN (
    select DISTINCT c3 from #Test ) c3List

答案 1 :(得分:1)

select concat(c1,':',c2,':',c3) from 
(select distinct c3 from t) as t3, 
(select distinct c2 from t) as t2, 
(select distinct c1 from t) as t1

答案 2 :(得分:-1)

select concat(c1,':',c2,':',c3) from ...