У меня есть такой набор данных;T-SQL несколько строк в столбцах
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
Но есть способ сделать это так, что если col_id
со значением 4 будет включен в таблицу, я хотел бы получить четвертый текстовый столбец без изменения запроса?
Это может [помощь] (http://stackoverflow.com/questions/30321217/sql -transpose-rows-to-undefined-number-of-columns) или [this] (http://stackoverflow.com/questions/15745042/efficiently-convert-rows-to-column s-in-sql-server/15745076 # 15745076) – ughai
Посмотрите это: http://sqlfiddle.com/#!6/91acb/1 – jpw
В любом случае, когда вы имеете дело с неизвестным количеством столбцов для транспонирования, вам нужно используйте динамический sql. – jpw