2013-02-05 184 views
1

我有三個表選擇具有最近的日期時間值的記錄

建築

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. 
+0

編輯這兩個查詢我都試過了,根據我在上面已經給出了表格的說明。 (讓他們更容易理解,更通用) – CRoshanLG

回答

1

嘗試

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) 
            FROM Transactions T 
            GROUP BY T.areaKey) 
+0

完美工作!謝謝你... 我編輯了你的答案,以匹配問題頂部由我給出的表格定義。 (我編輯了我也試過的東西。) 希望這會使問題更加通用,並且易於理解。 – CRoshanLG

2

這會給你的每一個建築面積最新的。

(PARTITION BY B.BuildingKey, a.areaKey ORDER BY T.TransactionDateTime DESC) RowID 
2
SELECT A.areaKey AS AreaKey, 
     A.areaID AS AreaID, 
     T.value AS CurrentValue, 
     T.trnDateTime AS RecordedDateTime     
FROM Areas A JOIN Buildings B ON B.buildingKey = A.buildingKey 
      JOIN Transactions T ON T.areaKey = A.areaKey 
WHERE @buildingKey = B.buildingKey AND EXISTS (
             SELECT 1 
             FROM Transactions T2 
             WHERE T.areaKey = T2.areaKey 
             GROUP BY T2.areaKey 
             HAVING MAX(T2.trnDateTime) = T.trnDateTime 
               ) 
+0

工作正常! Upvoted! – CRoshanLG