如何通过合并时间列将两个列表合并为复数列?

时间:2013-12-13 10:21:37

标签: sql tsql sql-server-2012

例如,我有很多表格[VV1][VV2]

[TimeStamp][V1]

2013-12-12 07:00:00.000 3628460,75
2013-12-12 09:00:00.000 3628460,75
2013-12-12 10:00:00.000 3628460,75
2013-12-12 11:00:00.000 3628460,75
2013-12-12 06:00:00.000 3628460,75

[TimeStamp][V2]

2013-12-12 07:00:00.000 3628460,75
2013-12-12 09:00:00.000 3628460,75
2013-12-12 10:00:00.000 3628460,75
2013-12-12 06:00:00.000 3628460,75

我希望得到类似的东西:

2013-12-12 07:00:00.000 3628460,75  3628460,75
2013-12-12 08:00:00.000 NULL        3628460,75
2013-12-12 09:00:00.000 3628460,75  3628460,75
2013-12-12 10:00:00.000 3628460,75  3628460,75
2013-12-12 11:00:00.000 3628460,75  NULL
2013-12-12 06:00:00.000 3628460,75  3628460,75

我尝试用连接实现它,我的变体非常可怕:

select distinct DATEADD(second, DATEDIFF(second, GETUTCDATE(), GETDATE()), coalesce(VV1.[TimeStamp], VV2.[TimeStamp])) as Date, V1, V2
from vv1
full join vv2
on vv2.TimeStamp = vv1.TimeStamp

(DATEDD是UTC到LOCAL时间)

之所以这样实现是因为表计数是动态的,每当我添加新表并希望看到新列时,我都可以轻松编辑选择字符串。

但是这个变种很糟糕,因为它填充了双倍而且有更多列,它只是变得疯狂而且不同的是肮脏的黑客合并......

现在我想到理智和快速实现......如何制作?

1 个答案:

答案 0 :(得分:1)

我认为不会有更好的解决方案,但下面的查询可能是一种更简洁的方式,特别是在添加新表时:

select [Date]
     , MAX([Value1]) as [Value1]
     , MAX([Value2]) as [Value2]

from (
    select DATEADD(second, DATEDIFF(second, GETUTCDATE(), GETDATE()), VV1.[TimeStamp]) as [Date]
         , V1 as [Value1]
         , Null as [Value2]
    from vv1

    UNION ALL

    select DATEADD(second, DATEDIFF(second, GETUTCDATE(), GETDATE()), VV2.[TimeStamp]) as [Date]
         , Null as [Value1]
         , V2 as [Value2]
    from vv2 ) subquery

group by subquery.date