将2个临时查询合并为1

时间:2017-07-21 03:56:08

标签: sql sql-server sql-server-2014

我尝试将2个查询合并为1.但是,我遇到了一些问题:

exec(@sql + @sql2 + @sql3)
exec(@sql4 + @sql5 + @sql6)

执行上述操作后,我得到以下结果:

enter image description here

但是,由于我想将2个查询合并为1使用日期,我写了几行,如下所示:

- 将2个查询加在一起进行比较

select a.stime as Date,
       a.bid as BidA,
       a.ask as AskA,
       b.bid as BidB,
       b.ask as AskB,
       ABS(ISNULL(a.bid, 0) - ISNULL(b.bid, 0)) as BidDiff,
       ABS(ISNULL(a.ask, 0) - ISNULL(b.ask, 0)) as AskDiff
from (exec(@sql + @sql2 + @sql3)) a left outer join (exec(@sql4 + @sql5 + @sql6)) b where a.stime = b.stime
Order by date DESC;

但是,我在exec附近不断收到错误的语法错误。

1 个答案:

答案 0 :(得分:0)

创建2个表变量(不确定您的数据类型是什么):

DECLARE @tableA AS TABLE([stime] AS datetime, [Bid] AS blah, [Ask] AS blah)
DECLARE @tableB AS TABLE([stime] AS datetime, [Bid] AS blah, [Ask] AS blah)

INSERT INTO @tableA
EXEC (@sql + @sql2 + @sql3)

INSERT INTO @tableB
EXEC (@sql4 + @sql5 + @sql6)

SELECT
    [A].[stime] AS [Date]
,   [A].[Bid] AS [BidA]
,   [A].[Ask] AS [AskA]
,   [B].[Bid] AS [BidB]
,   [B].[Ask] AS [AskB]
,   ABS(ISNULL([A].[Bid], 0) - ISNULL([B].[Bid], 0)) AS [BidDiff]
,   ABS(ISNULL([A].[Ask], 0) - ISNULL([B].[Ask], 0)) AS [AskDiff]
FROM @TableA AS [A]
LEFT JOIN @TableB AS [B]
    ON [A].[stime] = [B].[stime]
ORDER BY [A].[stime] DESC