T-SQL多行到列

时间:2015-05-19 11:04:40

标签: tsql

我有这样的数据集;

data_id     col_id      data_text_value
----------- ----------- ---------------
1           1           first first
1           2           first second
1           3           first third
2           2           second second

这是用于创建数据集的联合查询;

select 1 as data_id, 1 as col_id, 'first first' as data_text_value union all
select 1 as data_id, 2 as col_id, 'first second' as data_text_value union all
select 1 as data_id, 3 as col_id, 'first third' as data_text_value union all
select 2 as data_id, 2 as col_id, 'second second' as data_text_value

我希望查询的数据集将data_id分组为单行,其中所有col_id位于不同的列中;

with test as (
select 1 as data_id, 1 as col_id, 'first first' as data_text_value union all
select 1 as data_id, 2 as col_id, 'first second' as data_text_value union all
select 1 as data_id, 3 as col_id, 'first third' as data_text_value union all
select 2 as data_id, 2 as col_id, 'second second' as data_text_value
) 
select 
    distinct test.data_id,
    cid1_text,
    cid2_text,
    cid3_text
from 
    test 
    left outer join (select data_id, data_text_value as cid1_text from test where col_id=1) cid1 on test.data_id = cid1.data_id
    left outer join (select data_id, data_text_value as cid2_text from test where col_id=2) cid2 on test.data_id = cid2.data_id
    left outer join (select data_id, data_text_value as cid3_text from test where col_id=3) cid3 on test.data_id = cid3.data_id

我想要的结果是什么;

data_id     col_id      data_text_value
----------- ----------- ---------------
1           1           first first
1           2           first second
1           3           first third
2           2           second second

但是,有没有一种方法可以实现这一点,如果将值{4的col_id插入到表中,我会在不更改查询的情况下获得第四个文本列? < / p>

1 个答案:

答案 0 :(得分:2)

这是你正在寻找的吗?即使您插入更多数据,它也会起作用。 您的表

with test as (
select 1 as data_id, 1 as col_id, 'first first' as data_text_value union all
select 1 as data_id, 2 as col_id, 'first second' as data_text_value union all
select 1 as data_id, 3 as col_id, 'first third' as data_text_value union all
select 2 as data_id, 2 as col_id, 'second second' as data_text_value
) 

SELECT * INTO tbl_test
FROM test

实际查询

DECLARE @PivotCols VARCHAR(MAX);

SELECT @PivotCols = COALESCE(@PivotCols + ',','') + QUOTENAME(col_id)
FROM tbl_test
GROUP BY col_id
ORDER BY col_id

EXEC
(
'SELECT *
FROM tbl_test
PIVOT
(
    MAX(data_text_value) FOR col_id IN (' + @PivotCols + ')
) pvt
'

结果:

data_id     1             2             3
----------- ------------- ------------- -------------
1           first first   first second  first third
2           NULL          second second NULL