join n result stets水平

wljmcqd8  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(294)

我知道在这个主题上有很多问题,但似乎没有人能解决我的问题
很快,我想合并一个未知数量的结果集,如下面的示例所示
结果1:

Name |sum1 |sum2
________________
name1| 0.5 |0.1
name2| 0.6 |0.2

结果2:

Name |sum1 |sum2
________________
name1| 1.5 |0.7
name2| 1.6 |0.9

.
.
.

结果n:

Name |sum1 |sum2
________________
name1| 7.5 |9.7
name2| 8.6 |5.9

最后:

Name |sum1 |sum2| sum1 | sum2|.......| sum1|sum2
________________________________________
name1| 0.5 |0.1 | 1.5  | 0.7 |.......| 7.5 |9.7
name2| 0.6 |0.2 | 1.6  | 0.9 |.......| 8.6 |5.9

“name”列在所有结果中完全相同。
你们能帮忙吗?

e5nqia27

e5nqia271#

快速存储过程,动态生成查询字符串并执行它。您可以用第一个输入控制execute @in_run_query .

CREATE PROCEDURE dynamic_sql_query 
   @in_run_query INT 
,  @in_count_results_sets INT 
AS 
BEGIN 

IF @in_count_results_sets IS NULL 
 EXIT 

IF TRY_CONVERT(INT,@in_count_results_sets) IS NULL 
 EXIT 

 IF @in_count_results_sets < 2 
    BEGIN 
        SELECT 'Counter must be between 2 and 100'
        EXIT 
    END

IF @in_count_results_sets > 100 
    BEGIN 
        SELECT 'Build a better database'
        EXIT 
    END     

DECLARE @sql_string NVARCHAR(MAX) , @counter INT = 2 

SET @select = 'SELECT  r1.name, r1.sum1, r1.sum2'
SET @from = 'FROM result1 AS r1'

LOOP:

SET @prefix = 'r' + CAST(@counter AS String) 
SET @full_name = 'result' + CAST(@counter AS String) 
-- select 
SET @select = @select + ', ' + @prefix + '.name, ' + @prefix + '.sum1, ' + @prefix + '.sum2'
-- from 
SET @from = @from + '  join ' + @full_name + ' AS ' + @prefix + ' on r1.name = ' + @prefix + '.name'

IF @counter = @in_count_results_sets
     GOTO AppendStrings 

@counter = @counter + 1 

GOTO LOOP    

AppendStrings: 

SET @sql_string = @select + ' ' + @from + ';'

IF @in_run_query <> 1
    BEGIN 
        SELECT @sql_string 
        EXIT 
    END
 EXECUTE sp_executesql  @sql_string 
END
yfjy0ee7

yfjy0ee72#

你会用 join :

select r1.name, r1.sum1, r1.sum2, r2.sum1, r2.sum2, r3.sum1, r3.sum2
from result1 r1 join
     result2 r2
     on r1.name = r2.name join
     results r3
     on r1.name = r3.name

您需要为每个结果集继续此操作。
现在,有一个未知数量的结果集使这更复杂。这只需要基于相同的逻辑生成一个动态sql语句。

相关问题