2016-08-18 128 views
2

有這樣的數據:從第二臺如何通過第一臺獲得第二表值值

declare @test_names TABLE(id int identity(1,1), name character varying(50),age int); 
INSERT INTO @test_names(name,age) values ('name1',10),('name2',20); 

declare @test_names_details TABLE(id int identity(1,1), test_names_id int,col1 int,col2 int,col3 int); 

INSERT INTO @test_names_details(test_names_id,col1,col2,col3) 
VALUES(1,2,3,4),(1,5,6,7),(1,8,9,10),(2,20,21,22),(2,23,24,25); 

要選擇細節第一表值。怎麼做 ?輸出必須是這樣的:

field1  field2 field3 
name1  10  
2   3  4 
5   6  7 
8   9  10 
name2  20 
20   21  22 
23   24  25 

編輯

在表中我有許多行(1,名稱2,名稱3 ..)比如我只是寫他們兩個

+0

使用連接和分組方式無法實現所需的輸出。嘗試使用循環。 – Luftwaffe

+0

@Luftwaffe你能舉一些例子嗎?我不知道該怎麼做。我也編輯了問題。不需要我們怎麼做 – GeoVIP

+0

你想要輸出格式與上面相同嗎? – Luftwaffe

回答

1
DECLARE @output TABLE(field1 VARCHAR(50), field2 VARCHAR(50), field3 VARCHAR(50)) 
DECLARE @test_names_count INT, 
     @counter INT 
SELECT @test_names_count = COUNT(1) FROM @test_names 
SET @counter = 1 

WHILE (@counter <= @test_names_count) 
BEGIN 
    INSERT INTO @output SELECT name, age, '' FROM @test_names WHERE id = @counter 
    INSERT INTO @output SELECT col1, col2, col3 FROM @test_names_details WHERE test_names_id = @counter 

    SET @counter = @counter + 1 
END 

SELECT * FROM @output 
0

更新的任何名字列數:基於

組解決方案,與您所選擇的名稱替換列名

;with sortorder 
as(
select name,age,min(col1)-1 as mincol 
from @test_names t 
join 
@test_names_details t1 
on t.id=t1.test_names_id 
group by name,age 
) 
select * from sortorder 
union all 
select cast(col1 as varchar(5)),cast(col2 as varchar(5)),cast(col3 as varchar(5)) from @test_names_details 
order by mincol 
+0

這樣的結果我在表中有許多行(name1,name2,name3 ...),並且不能按順序寫入所有行 – GeoVIP

+0

你能舉例說明它將如何用於更多行嗎? – GeoVIP

相關問題