2017-10-04 61 views
0

分組這是MyTable的數據基礎上連續3行的分鐘(時間):如何選擇它們按日期

select Name, LastName, Id, LocationId, Date, Time, RN from mytable 


Name LastName Id LocationId Date  Time  RN 
Office Jones  284 NY   20171004 1540  1 
Office Jones  284 NY   20171004 1545  2 
Office Jones  284 NY   20171004 1550  3 

Office Jones  284 NY   20171004 1650  4 

Office Jones  284 NY   20171113 1030  1 
Office Jones  284 NY   20171113 1035  2 
Office Jones  284 NY   20171113 1040  3 

Office Jones  284 NY   20171113 1130  4 
Office Jones  284 NY   20171113 1135  5 
Office Jones  284 NY   20171113 1140  6 

Office Jones  284 NY   20171113 1230  7 
Office Jones  284 NY   20171113 1435  8 
Office Jones  284 NY   20171113 1740  9 

Office Jones  284 NY   20171113 1840  10 

Office Jones  284 NY   20171115 1030  1 
Office Jones  284 NY   20171115 1035  2 
Office Jones  284 NY   20171115 1040  3 

我想展示我的結果作爲名稱,名字,身份證, LocationId,日期,在此基礎上按日期分組連續3個排分鐘(時間)

Name LastName Id LocationId Date  Time 
Office Jones  284 NY   20171004 1540 
Office Jones  284 NY   20171113 1030 
Office Jones  284 NY   20171113 1130 
Office Jones  284 NY   20171113 1230 
Office Jones  284 NY   20171115 1030 

這是我迄今爲止,但我無法弄清楚如何得到其他2行到我結果

SELECT Name, LastName, Id, LocationId, Date, min(Time) as Time FROM mytable 
WHERE Date IN (SELECT Date 
         FROM mytable 
         WHERE RN = 3) 
GROUP BY Name, LastName, Id, LocationId, Date 



Name LastName Id LocationId Date  Time 
Office Jones  284 NY   20171004 1540 
Office Jones  284 NY   20171113 1030 
Office Jones  284 NY   20171115 1030 
+0

是不是你的WHERE RN = 1'的結果數據? –

回答

2

如何使用算術rn

select name, lastname, id, locationid, date, min(time) 
from t 
group by name, lastname, id, locationid, 
     (rn - 1)/3; 

或者,只需where

select name, lastname, id, locationid, date, time 
from t 
where rn % 3 = 1; 
0

這裏是一個簡化版本刪除常數值列,只專注於計算所需的列(我會傾入臨時表)。內部聯接中的派生表確定最大行數,每個日期是三的倍數,並且由三個結果集羣在外部查詢的分組上:

select #tmp.dates, 
     min(#tmp.times) 
from #tmp 
inner join (select dates, 
        max(rnum) rnum_x 
      from #tmp 
      where rnum % 3 = 0 
      group by dates) x 
    on #tmp.dates = x.dates 
    and #tmp.rnum <= x.rnum_x 
group by #tmp.dates, 
     case when rnum%3 = 0 
       then rnum/3 - 1 
     else rnum/3 
     end 
相關問題