0

例如:

我有疑问:

select coalesce(VV1.[TimeStamp], VV2.[TimeStamp]...) as MyDate, V1, V2, .. VN
    from VV1
    full join VV2
    full join VV3
    ...
    full outer join VVN
    on VV1.TimeStamp = VV2.TimeStamp
    and VV2.TimeStamp = VV3.TimeStamp
    ... 
    and VVN-1.TimeStamp = VVN.TimeStamp

我想将它生成为字符串,但它的on一部分很复杂......所以

  • 是否有可能以更好的方式编写它?
  • 也许以某种方式写on AllOfThemAreEqual(VV1.TimeStamp, VV2.TimeStamp .. VVN.TimeStamp)?但我怀疑这是否可能:(
  • 也许可以将以前的值存储在临时变量中,然后从那里提取?最后一个选项对我来说看起来最真实。

SQLFibble:http ://sqlfiddle.com/#!6/4e138/3/0

CREATE TABLE T1(
    [ValueId] [bigint] IDENTITY(1,1) NOT NULL,
    [PointId] [int] NULL,
    [Value] [int] NULL,
    [TimeStamp] [datetime] NULL
  );

INSERT INTO T1
           ([PointId]
           ,[Value]
           ,[TimeStamp])
     VALUES
           (1, 1, 1900-01-01)
INSERT INTO T1
           ([PointId]
           ,[Value]
           ,[TimeStamp])
     VALUES
           (2, 2, 1900-01-01)
;

WITH VV1 AS  (
            SELECT  [TimeStamp], [Value] AS V1 FROM T1
            WHERE   [PointId] = 1
        ), VV2 AS  (
            SELECT  [TimeStamp], [Value] AS V2 FROM T1
            WHERE   [PointId] = 2
        )
SELECT
  coalesce(VV1.[TimeStamp], VV2.[TimeStamp]) AS dt
  , V1, V2
FROM VV1
FULL JOIN VV2
ON VV1.TimeStamp = VV2.TimeStamp
4

1 回答 1

3

使用你的小提琴:http ://sqlfiddle.com/#!6/4e138/3/0

这是一种不同的方法。无需额外的连接,只需为每个Timestamp.

SELECT "Timestamp"
     , Max(CASE WHEN PointId = 1 THEN "Value" END) As V1
     , Max(CASE WHEN PointId = 2 THEN "Value" END) As V2
     , Max(CASE WHEN PointId = 3 THEN "Value" END) As V3
     , Max(CASE WHEN PointId = 4 THEN "Value" END) As V4
     , Max(CASE WHEN PointId = 5 THEN "Value" END) As V5
FROM   t1
GROUP
    BY "Timestamp"

请尽量避免使用动态 SQL

于 2013-10-14T12:49:15.343 回答