横向合并n个结果集

时间:2018-07-25 20:46:24

标签: mysql sql pivot full-outer-join

我知道有关此主题的问题很多,但似乎没人能解决我的问题

很快,我想像下面的示例一样水平合并数量未知的结果集

结果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

“名称”列在所有结果中完全相同。

觉得你们可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您将使用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语句即可。

答案 1 :(得分:0)

快速存储过程可动态构建查询字符串并执行它。您可以使用第一个输入@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