2016-06-29 46 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" 

如果我猜测错了,我认为这将是有益的,如果你能提供的样本数据和实例结果将