2013-01-03 155 views
1

我想爲每個15分鐘時間值的最接近值做一個SQL SELECT。例如:SQL SELECT Only最接近15分鐘時間戳

00:15, 
00:30, 
00:45, 
01:00, 
01:15 etc... 

基於被時間戳(時間)不太上加蓋00秒內使用下列如果設法降低輪的每一個值最接近的15分鐘,但我只想要一個最接近例如

SELECT dateadd(minute, -1 * datediff(minute, 0, 
    cast(convert(varchar(20),[time],100) as smalldatetime)) % 15, 
    dateadd(minute, datediff(minute, 0, [time]), 0)) as [TIMESTAMP], 
    cast(convert(varchar(20),[time],100) as smalldatetime), [time], 
    tagname , value 
FROM hdata 
INNER JOIN rtdata 
    ON hdata.tag_id = rtdata.id 
WHERE tagname = 'M1_WH_004' 
order by [TIMESTAMP] desc 

(注:我需要的內連接到拉該標記名,因爲它們不是在HDATA表)

生產:

example data

因此,每次15分鐘,我只想要最接近15分鐘邊界的值。對於上述數據,09:45:15.383和09:30:17.463分別爲09:45和09:30的數據。

我需要子查詢還是case語句? 任何幫助將不勝感激!

此外到這一點,有這樣看上去像數據在溶液中的表(由每15分鐘的數據)已經和子查詢基於最後兩個值,像這樣進行計算:

SELECT DD1.[TIME_STAMP] AS [TIME_STAMP], DD1.[kWh1] AS [kWh1], DD1.[kWh2] AS [kWh2], (DD1.[kWh1] + DD1.[kWh2]) AS [Total] FROM (SELECT a.ID 
     ,a.TIME_STAMP 
     ,(a.[1_M1_Wh] - (SELECT TOP 1 b.[1_M1_Wh] FROM TagCapture b WHERE b.TIME_STAMP = DATEADD(MINUTE, -15, a.TIME_STAMP))) * 0.04 AS kWh1 
     ,(a.[1_M2_Wh] - (SELECT TOP 1 b.[1_M2_Wh] FROM TagCapture b WHERE b.TIME_STAMP = DATEADD(MINUTE, -15, a.TIME_STAMP))) * 0.04 AS kWh2 
    FROM [TagCapture] a) DD1 

我如何使用此查詢中提供的解決方案?我有點困惑於所有的子查詢。

即所以基於由t子查詢定義的數據取從前一個15分鐘減去的計數值,並乘以得到所需的值我將在哪裏插入每個FROM子句中的t子查詢?我似乎無法得到它的工作。以上就是t查詢爲'M1'和'M2'定義兩個不同標記名的地方。

再次提前致謝!

回答

1

它看起來像你正在使用SQL Server。如果是這樣,那麼你可以使用row_number()來解決這個問題。

select t.* 
from (select t.*, row_number() over (partition by tagname, time15 order by time) as seqnum 
     from (SELECT dateadd(minute, -1 * datediff(minute, 0, cast(convert(varchar(20),[time],100) as smalldatetime)) % 15, dateadd(minute, datediff(minute, 0, [time]), 0)) as [TIMESTAMP], cast(convert(varchar(20),[time],100) as smalldatetime) as time15, 
        [time], tagname , value 
      FROM hdata INNER JOIN rtdata 
       ON hdata.tag_id = rtdata.id 
      WHERE tagname = 'M1_WH_004' 
     ) t 
    ) t 
where seqnum = 1 
+0

稀釋是這個工作只是需要將其更改爲[TIMESTAMP] [時間]順序[TIMESTAMP]是一個越來越向下取整爲15分鐘邊界「time15」實際上應該是「時間min」只是四捨五入(分鐘,-1 * datediff(分鐘,分鐘,分鐘,分鐘)分鐘:從選擇t。*,row_number()over(按標記名分區,[TIMESTAMP] order by [time])中選擇t。* 0,cast(convert(varchar(20),[time],100)as smalldatetime))%15,dateadd(minute,datediff(minute,0,[time]),0))as [TIMESTAMP] (varchar(20),[time],100)as smalldatetime)timemin,[time],tagname,value ... – user1801843

+0

謝謝你的幫助! – user1801843

+0

你能幫我解決上述問題嗎? – user1801843