我有三张桌子
建筑物
BuildingKey(int) | BuildingID(varchar) | ...
领域
areaKey(int) | areaID(varchar) | buildingKey(int-FK[Buildings]) | ...
交易
transactionKey(int) | areaKey(int-FK[Areas]) | value(float) | trnDateTime(DateTime)
Areas
一个中
可能有几个Building
。
各个领域都有很多Transactions
,value
各有千秋trnDateTime
。
我想要做的是获取每个a的最新value
(事务)(当给出时)。 Area
Building
buildingKey
我提到了一些以前的问题,比如这个,并尝试了以下问题。
(1)
DECLARE @buildingKey INT
SET @buildingKey = 3
;WITH Vals AS (
SELECT T.areaKey AS AreaKey,
T.value AS CurrentValue,
T.trnDateTime AS RecordedDateTime,
ROW_NUMBER() OVER (PARTITION BY B.buildingKey ORDER BY T.trnDateTime DESC) RowID
FROM Buildings B INNER JOIN
Areas A ON B.buildingKey = A.buildingKey INNER JOIN
Transactions T ON A.areaKey = T.areaKey
WHERE B.buildingKey = @buildingKey
)
SELECT AreaKey,
CurrentValue,
MAX(RecordedDateTime) AS RecentReading,
RowID
FROM Vals
WHERE RowID = 1
GROUP BY AreaKey, CurrentValue, RowID
!) 返回最新值(在所有区域中);不是每个区域的最新值!
(2)
DECLARE @buildingKey INT
SET @buildingKey = 3
SELECT A.areaKey AS AreaKey,
A.areaID AS AreaID,
T.value AS CurrentValue,
T.trnDateTime AS RecordedDateTime
FROM Areas A, Buildings B, Transactions T
WHERE @buildingKey = B.buildingKey AND
B.buildingKey = A.buildingKey AND
T.areaKey = A.areaKey AND
T.trnDateTime IN (SELECT MAX(T.trnDateTime), T.areaKey
FROM Transactions T
GROUP BY T.areaKey)
!) 给出一个错误 -->
Msg 116, Level 16, State 1, Line 16
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.