我如何加入这些表格?

bri*_*tey 0 sql sql-server join

我有许多设备在不同的时间记录不同的数据,并希望在一个查询中获取所有数据,按时间排序.我所拥有的各种表格的一个例子:

CREATE TABLE location(
    device_id INT, -- REFERENCES device(id)
    timestamp DATETIME2 NOT NULL,
    position GEOMETRY NOT NULL
)

CREATE TABLE temperature(
    device_id INT, -- REFERENCES device(id)
    timestamp DATETIME2 NOT NULL,
    temp FLOAT NOT NULL
)
Run Code Online (Sandbox Code Playgroud)

我希望有一个单独的查询连接在device_id和timestamp上的表,当时间戳不匹配时,它包含空值.我正在寻找的输出格式的一个例子是:

device_id, timestamp, location, temperature
1, 2011/12/1 10:00:00, (35.1, 139.2), NULL
1, 2011/12/1 10:00:01, NULL, 9.0
1, 2011/12/1 10:00:02, (35.1, 139.2), 9.1
Run Code Online (Sandbox Code Playgroud)

我已经尝试过FULL JOIN但是无法弄清楚如何在没有巨大的CASE语句的情况下执行timestamp列(请记住,虽然我只显示了2个表,但是可以有更多表).

SELECT 
    location.device_id, 
    CASE WHEN location.timestamp IS NOT NULL THEN
        location.timestamp
    ELSE 
        temperature.timestamp 
    END as timestamp, 
    location,
    temp
FROM
    location 
    FULL JOIN temperature ON location.device_id = temperature.device_id 
        AND location.timestamp = temperature.timestamp
ORDER BY
    timestamp
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法来编写这种查询?

Alb*_*nbo 5

您可以使用COALESCE表达式.

SELECT 
    location.device_id, 
    COALESCE(location.timestamp, temperature.timestamp) as timestamp, 
    position,
    temp
FROM
    location 
    FULL JOIN temperature ON location.device_id = temperature.device_id 
        AND location.timestamp = temperature.timestamp
ORDER BY
    timestamp;
Run Code Online (Sandbox Code Playgroud)