[英]how to join columns of two different tables
我有两个表,称为概述和 current_voltage。 我想在单个表 output 中获得两个不同表的前 1 条记录。
sql 查询
select top 1 VL1,VL2,VL3 from current_voltage
where deviceimei ='233'
order by devicetimestamp desc
union
select top 1 OTI,WTI,ATI from overview
where deviceimei ='233'
order by devicetimestamp desc
请求操作
VL1,VL2,VL3,OTI,WTI,ATI
234,235,234,25,24,25
一个简单的 JOIN 就可以了。 这里我们 go:
SELECT TOP 1 cv.VL1, cv.VL2, cv.VL3, ov.OTI, ov.WTI, ov.ATI
FROM current_voltage cv
JOIN overview ov
ON cv.deviceimei = ov.deviceimei
WHERE cv.deviceimei ='233'
ORDER BY cv.devicetimestamp DESC, ov.devicetimestamp DESC
要阅读有关 sql 中的 JOIN 的更多信息,请参阅此
您需要 2 个查询的交叉连接:
select t1.*, t2.*
from (
select top 1 VL1,VL2,VL3 from current_voltage
where deviceimei ='233'
order by devicetimestamp desc
) t1 cross join (
select top 1 OTI,WTI,ATI from overview
where deviceimei ='233'
order by devicetimestamp desc
) t2
您还可以使用横向连接:
select vc.*, ov.*
from current_voltage cv cross apply
(select top (1) ov.*
from overview ov
where ov.deviceimei = cv.deviceimei
order by ov.devicetimestamp desc
) ov
where ov.deviceimei ='233'
order by cv.devicetimestamp desc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.