2016-06-29 69 views
0

我有一個查詢爲:被反覆對每一個GRPSQL窗口函數:MAX(日)在PARTITION BY子句

select 
    location_id, 
    max(created) over (partition by location_id) as "created" 
from 
    device 
group by 
    location_id, created 
order by 
    location_id 

這將導致最大的日期。

21 2015-01-26T18:25:00.000Z
22 2015-10-18T13:21:32.000Z
22 2015-10-18T13:21:32.000Z
22 2015-10- 18T13:21:32.000Z

現在,如果我計算日期之間的差值:

select 
    location_id, 
    date(created), 
    max(date(created)) - min(date(created)) over (partition by location_id) as "created" 
from 
    device 
group by 
    location_id, created 
order by 
    location_id 

21 2015-01-26T0 0:00:0 00.000Z
22 2015-01-26T00:00:0 00.000Z
22 2015-03-12T00:00:45 00.000Z
22 2015-10-18T00:00:00.000Z 265

爲什麼我會得到第一個記錄和第二個,然後第三個之間的區別?爲什麼不只是通過組重複最大 - 最小的差異?

希望我對這個問題很清楚。

+1

哪個RDBMS是爲了這個?請添加一個標籤來指定您是使用'mysql','postgresql','sql-server','oracle'還是'db2' - 或者其他的東西。 –

回答

2

你的第二個查詢被解析如下:

select . . . 
     (max(date(created)) - 
     min(date(created)) over (partition by location_id) 
     ) as "created" 
. . . 

也就是說,窗口子句只適用於min()。我認爲你打算:

select . . . 
     (max(date(created) over (partition by location_id) - 
     min(date(created)) over (partition by location_id) 
     ) as "created" 
. . . 
+0

它工作。謝謝! – Peppy

0

在您的查詢中,您按位置進行分區 - 所以基本上最小和最大值將在上下文中考慮到各個位置......這也許可以解釋,爲什麼每行都有最小值和最大值。

0

我認爲這是因爲您沒有在第二個查詢中使用Max的窗口函數。

嘗試:

max(date(created)) over (partition by location_id) - min(date(created)) over (partition by location_id) as "created" 

如果我猜測錯了,我認爲這將是有益的,如果你能提供的樣本數據和實例結果將