我有三個表選擇具有最近的日期時間值的記錄
建築
BuildingKey(int) | BuildingID(varchar) | ...
地區
areaKey(int) | areaID(varchar) | buildingKey(int-FK[Buildings]) | ...
交易
transactionKey(int) | areaKey(int-FK[Areas]) | value(float) | trnDateTime(DateTime)
Building
中可能有幾個Areas
。
所有地區有很多Transactions
,不同的value
和不同的trnDateTime
。
我想要做的就是讓每個Area
一個Building
(當buildingKey
被給予)的最新value
(事務)。
我提到了一些以前的問題,例如this one,並試着關注。 !
(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.
編輯這兩個查詢我都試過了,根據我在上面已經給出了表格的說明。 (讓他們更容易理解,更通用) – CRoshanLG