使用TIMESTAMP的SQL Server中的表联接问题

时间:2018-12-30 06:18:01

标签: sql sql-server join timestamp

我想从SQL Server的三个表中获取当前日期的详细信息。我无法使用TIMESTAMP来加入表格,TIMESTAMP在每个表格中都是不同的。加入这些表没有共同因素。有什么办法可以连接这些表。而且我也不能修改表,这些表来自第三方服务。

查询:

SELECT * 
FROM table1 
WHERE CAST(TIMESTAMP AS DATE) = CAST(GETDATE() AS DATE) 
ORDER BY CAST(TIMESTAMP AS DATETIME2(0))

SELECT * 
FROM table2 
WHERE CAST(TIMESTAMP AS DATE) = CAST(GETDATE() AS DATE) 
ORDER BY CAST(TIMESTAMP AS DATETIME2(0))

SELECT * 
FROM table3
WHERE CAST(TIMESTAMP AS DATE) = CAST(GETDATE() AS DATE) 
ORDER BY CAST(TIMESTAMP AS DATETIME2(0))

SELECT 
    CAST(one.TIMESTAMP AS DATETIME2(0)) AS DATE,
    CONVERT(DECIMAL(10, 2), one.value) AS v1, 
    CONVERT(DECIMAL(10, 2), two.VALUE) AS v2, 
    CONVERT(DECIMAL(10, 2), three.VALUE) AS v3 
FROM
    table1 one 
LEFT JOIN 
    table2 two ON CAST(one.TIMESTAMP AS DATETIME2(0)) = CAST(two.TIMESTAMP AS DATETIME2(0)) 
LEFT JOIN 
    table3 three ON CAST(one.TIMESTAMP AS DATETIME2(0)) = CAST(three.TIMESTAMP AS DATETIME2(0))
WHERE
    CAST(one.TIMESTAMP AS DATE) = CAST(GETDATE() AS DATE) 
ORDER BY
    CAST(one.TIMESTAMP AS DATETIME2(0))

结果:

enter image description here

我没有得到第二张表和第三张表的数据。例如:2018-12-30 00:00:15.657这次是从第三张表的第一行开始。结果没有显示出来。我想要所有数据。

希望您能理解。您能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

您可能需要full join

SELECT COALESCE(CAST(one.TIMESTAMP AS DATETIME2(0)),
                CAST(two.TIMESTAMP AS DATETIME2(0)),
                CAST(three.TIMESTAMP AS DATETIME2(0))
               ) as dt,
       CONVERT(DECIMAL(10, 2), one.value) AS v1, 
       CONVERT(DECIMAL(10, 2), two.VALUE) AS v2, 
       CONVERT(DECIMAL(10, 2), three.VALUE) AS v3 
FROM (SELECT *
      FROM table1 one
      WHERE CAST(one.TIMESTAMP AS DATE) = CAST(GETDATE() AS DATE)
     ) one FULL JOIN 
     (SELECT *
      FROM table2 two
      WHERE CAST(two.TIMESTAMP AS DATE) = CAST(GETDATE() AS DATE)
     ) two
     ON CAST(two.TIMESTAMP AS DATETIME2(0)) = CAST(on.TIMESTAMP AS DATETIME2(0)) FULL JOIN
     (SELECT *
      FROM table3 three
      WHERE CAST(three.TIMESTAMP AS DATE) = CAST(GETDATE() AS DATE)
     ) three
     ON CAST(three.TIMESTAMP AS DATETIME2(0)) = COALESCE(CAST(one.TIMESTAMP AS DATETIME2(0)), CAST(one.TIMESTAMP AS DATETIME2(0)))
ORDER BY dt;

FULL JOIN在过滤方面比较棘手,这就是为什么它使用子查询的原因。

答案 1 :(得分:0)

或者,只需修改WHERE

WHERE
    CAST(one.TIMESTAMP AS DATE) = CAST(GETDATE() AS DATE) 
 OR CAST(two.TIMESTAMP AS DATE) = CAST(GETDATE() AS DATE) 
 OR CAST(three.TIMESTAMP AS DATE) = CAST(GETDATE() AS DATE)