我有两个数据库,一个数据库每1分钟记录一次水箱水位。我们有大约30辆坦克。另一个数据库包含查找表,其中包含给定级别的加仑数或每个罐。
我已经设法使用INNER JOIN
从SQL Server 2012中的查找表中获取数据
WITH T1 As
(
SELECT
DateTime, TagName, Value
FROM
INSQL.Runtime.dbo.History
WHERE
DateTime = (SELECT Max(DateTime)
FROM INSQL.Runtime.dbo.History
WHERE TagName LIKE 'LT%')
AND TagName LIKE 'LT%' AND Value <> '0'
),
T2 AS
(
SELECT *
FROM TankSTrappingDB.dbo.StrappingTable
)
SELECT *
FROM T1
LEFT JOIN T2 ON T1.TagName = T2.TagName
WHERE T2.LIT_PV <= T1.Value
然而,这会返回表2中的所有行,其中tank中实际级别的值小于表1中记录的值。我只需要表2中与该列最接近的一行。表中记录的值与相应的时间戳记。
答案 0 :(得分:0)
不是将T2连接到T2,而是可以在TAGname匹配的T2中查找MAX(LIT_PV)?但是,如果您还需要T2表中的其他值,则可以在SQL
中的最后一位添加另一个测试 ... ...
SELECT *
FROM T1
LEFT JOIN T2 ON T1.TagName = T2.TagName
WHERE T2.LIT_PV <= T1.Value
and T2.LIT_PV in
(select max(T2A.LIT_PV) from T2 T2A
where T1.TagName = T2A.TagName and T2A.LIT_PV <= T1.Value
)
答案 1 :(得分:0)
请尝试以下查询。由于样本数据不可用,我无法测试此查询。
WITH T1 As
(
SELECT
DateTime, TagName, Value,
ROW_NUMBER() OVER (PARTITION BY TagName ORDER BY DateTime DESC) RN
FROM
INSQL.Runtime.dbo.History
WHERE
TagName LIKE 'LT%' AND Value <> '0'
),
T2 AS
(
SELECT *,
ROW_NUMBER() OVER(ORDER BY T.LIT_PV DESC) RN
FROM TankSTrappingDB.dbo.StrappingTable T
INNER JOIN T1 ON T1.TagName = T.TagName
AND T.LIT_PV <= T1.Value
WHERE T1.RN = 1
)
SELECT *
FROM T1
INNER JOIN T2 ON T1.TagName = T2.TagName
AND T1.RN = T2.RN
WHERE T2.RN = 1