【问题标题】:How to get second table values by first table values如何通过第一个表值获取第二个表值
【发布时间】:2016-08-18 19:49:35
【问题描述】:

有类似的数据:

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

已编辑

在表中我有很多行 (name1,name2,name3..) 例如我只写了其中的两个

【问题讨论】:

  • 使用 Joins 和 Group By 无法实现您想要的输出。尝试使用循环。
  • @Luftwaffe 你能举个例子吗?我不知道该怎么做。我还编辑了问题。没必要怎么做
  • 你想输出和上面一样的格式吗?
  • @Luftwaffe 在我将连接这个字符串之后。现在我只需要有问题的结果

标签: sql-server sql-server-2008 tsql


【解决方案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

【讨论】:

    【解决方案2】:

    针对任意数量的名称列进行了更新:

    基于集合的解决方案,将列名替换为您选择的名称

    ;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
    

    【讨论】:

    • 我在表中有很多行 (name1,name2,name3 ...) 并且不能按顺序写
    • 你能给我举个例子吗? 更多行?
    猜你喜欢
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2022-10-03
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多