表T1序号 字段1 字段2 字段3
1 a1 c 2.3
2 aa c 1.2
3 ba b 4.2
4 b1 b 5.8
5 ac c 0.1
6 ae c 4.5如果想按字段2分组统计字段3的合计,然后再按序号的前后顺序来排,应该怎么写呢!~结果希望是这样:
字段1 字段2 字段3
a1 c 2.3
aa c 1.2
ac c 0.1
ae c 4.5
c 8.1
ba b 4.2
b1 b 5.8
b 10
1 a1 c 2.3
2 aa c 1.2
3 ba b 4.2
4 b1 b 5.8
5 ac c 0.1
6 ae c 4.5如果想按字段2分组统计字段3的合计,然后再按序号的前后顺序来排,应该怎么写呢!~结果希望是这样:
字段1 字段2 字段3
a1 c 2.3
aa c 1.2
ac c 0.1
ae c 4.5
c 8.1
ba b 4.2
b1 b 5.8
b 10
select
column1,column2,column3
from
(
select min(id) as seq,
null as column1,
column2,
sum(column3) as column3
from t1
group by column2
union all
select min(id) over(partition by column2 order by id) as seq,
column1,
column2,
column3
from t1
) result1
order by seq,column2,column1 nulls last
1、按照‘字段2’分组,用最小的‘序号’作为整组的‘序号’;
2、按照‘字段2’分组,统计字段3的合计,同时取出组的最小‘序号’,外加造一个空值。有一小点好像失误,order by之后的结果:
序号 字段1 字段2 字段3
4 b1 b 5.8
3 ba b 4.2
b 10
1 a1 c 2.3
2 aa c 1.2
5 ac c 0.1
6 ae c 4.5
c 8.1
与楼主要求的好像有点不符!应该是下面的结果才对吧?!
序号 字段1 字段2 字段3
1 a1 c 2.3
2 aa c 1.2
5 ac c 0.1
6 ae c 4.5
c 8.1
3 ba b 4.2
4 b1 b 5.8
b 10
----------------------------1
我认为应该在内核sql中巴把‘序号’字段也取出来!order by的时候,只需要order by seq,id就可以了。
如----------------------------2
select
column1,column2,column3
from
(
select null as 序号, --追加
min(id) as seq,
null as column1,
column2,
sum(column3) as column3
from t1
group by column2
union all
select 序号, --追加
min(id) over(partition by column2 order by id) as seq,
column1,
column2,
column3
from t1
) result1
order by seq,序号 --变更
n_n