5

假设我有一张t这样填充的表格:

x y z 
- - - 
A 1 A 
A 4 A 
A 6 B 
A 7 A 
B 1 A 
B 2 A 

基本上,列 x 和 z 是随机字母和 y 随机数。

我想按如下方式聚合行:

x z min(y) max(y)
- - ------ ------
A A 1      4
A B 6      6
A A 7      7
B A 1      2

换句话说:假设行按 x、y 和 z 排序,请为每个连续的 x 和 z 组选择最小和最大 y。

请注意,此查询不是我需要的:

select x, z, min(y), max(y)
from t
group by x, z

因为这会导致以下不需要的结果:

x z min(y) max(y)
- - ------ ------
A A 1      7
A B 6      6
B A 1      2

所以问题是:有没有办法在 SQL 中表达我想要的东西?

(如果解决方案依赖于 SQL 方言:Oracle 解决方案将是首选。)

4

3 回答 3

2

这是一个解决方案,但我没有时间一步一步地解释它:

select x, z, min(y), max(y)
from (
  select b.* , sum(switch) over (order by rn) as grp_new 
  from(
    select a.* , 
           case when grp = (lag(grp) over (order by rn))
           then 0 
           else 1 end as switch
    from 
        (select x,y,z, 
                dense_rank() over (order by x, z) as grp,
                row_number() over (order by x, y, z) rn
         from t
    )a
  )b
)c
group by x, z, grp_new
order by grp_new

SQLFIDDLE 来测试它。

于 2013-09-26T12:32:55.037 回答
1

如果您的版本支持WITHROW_NUMBER() OVER ,您没有提及 Oracle 版本

WITH C as
(
select t.*,
       ROW_NUMBER() OVER (order by x,y,z ) as rn
from t
), C2 as 

(
select t1.*,
( 
  select count(*) from c where Rn<=t1.Rn 
                               and (z<>t1.z or x<>t1.x) 
) as Grp
from c t1
) 

select x,z,min(y),max(y) from c2 
group by x,z,grp
order by min(rn)

SQLFiddle 演示

于 2013-09-26T12:27:02.360 回答
0

尝试

select x, z, min(y), max(y)
  from (select x, z, y from t order by x, z))
 group by x, z
于 2013-09-26T12:04:05.857 回答