有人知道这是否可行。我有这张桌子:
+---------+--------+----------+---------------+ | SOR_NUM | SOR_ID | SOR_COST | SOR_LINE_COST | +---------+--------+----------+---------------+ | 7 | 1 | 10 | 35 | | 7 | 1 | 10 | 37 | | 7 | 1 | 10 | 39 | | 7 | 2 | 20 | 35 | | 7 | 2 | 20 | 32 | +---------+--------+----------+---------------+
我想得到小计(可能有分组集),如下所示:
+---------+---------------+----------+---------------+ | SOR_NUM | SOR_ID | SOR_COST | SOR_LINE_COST | +---------+---------------+----------+---------------+ | 7 | 1 | 10 | 35 | | 7 | 1 | 10 | 37 | | 7 | 1 | 10 | 39 | | 7 | Total SOR_ID | 10 | 111 | | 7 | 2 | 20 | 35 | | 7 | 2 | 20 | 32 | | 7 | Total SOR_ID | 20 | 67 | | 7 | Total SOR_NUM | 30 | 178 | +---------+---------------+----------+---------------+
答案 0 :(得分:0)
您可以查看Oracle SQL functions for Aggregation的ROLLUP
和GROUPING
函数。
下面的查询给出了您想要的输出,但是会发生一些SOR_COST
的调整。我将此归因于您的数据未充分规范化的事实。
select sub2.sor_num,
case when sub2.sor_id is null then 'Total SOR_ID'
when sub2.sor_cost is null then 'Total SOR_NUM'
else to_char(sub2.sor_id) end sor_id,
nvl(sub2.sor_cost, sub2.sum_sub1_one_sor_cost) sor_cost,
nvl(sub2.sor_line_cost, sub2.sum_sub2_sum_sor_line_cost) sor_line_cost
from (select case when (grouping(sub1.sor_num) = 0 and
grouping(sub1.sor_id) = 0 and
grouping(sub1.sor_cost) = 0 and
grouping(sub1.sor_line_cost) = 0) then 1
when (grouping(sub1.sor_num) = 0 and
grouping(sub1.sor_id) = 1 and
grouping(sub1.sor_cost) = 1 and
grouping(sub1.sor_line_cost) = 1) then 2
else 0 end show_row,
max(sub1.sor_id) ord,
sub1.sor_num,
sub1.sor_id,
sub1.sor_cost,
sum(sub1.one_sor_cost) sum_sub1_one_sor_cost,
sub1.sor_line_cost,
sum(sub1.sum_sor_line_cost) sum_sub2_sum_sor_line_cost
from (select grouping(x.sor_num) grp_1,
grouping(x.sor_id) grp_2,
grouping(x.sor_cost) grp_3,
grouping(x.sor_line_cost) grp_4,
x.sor_num,
x.sor_id,
x.sor_cost,
nvl2(x.sor_cost, null, min(x.sor_cost)) one_sor_cost,
sum(x.sor_line_cost) sor_line_cost,
nvl2(x.sor_line_cost, null, sum(x.sor_line_cost)) sum_sor_line_cost
from (select 7 sor_num, 1 sor_id, 22 sor_cost, 35 sor_line_cost from dual union all
select 7 sor_num, 1 sor_id, 22 sor_cost, 37 sor_line_cost from dual union all
select 7 sor_num, 1 sor_id, 22 sor_cost, 39 sor_line_cost from dual union all
select 7 sor_num, 2 sor_id, 22 sor_cost, 35 sor_line_cost from dual union all
select 7 sor_num, 2 sor_id, 22 sor_cost, 32 sor_line_cost from dual) x
group by x.sor_num,
x.sor_id,
rollup(x.sor_cost, x.sor_line_cost)) sub1
where ((sub1.grp_3 = 1 and sub1.grp_2 = 0 and sub1.grp_1 = 0) or
(sub1.grp_1 = 0 and sub1.grp_2 = 0 and sub1.grp_3 = 0 and
sub1.grp_4 = 0))
group by rollup(sub1.sor_num,
sub1.sor_id,
sub1.sor_cost,
sub1.sor_line_cost)) sub2
where sub2.show_row > 0
order by sub2.sor_num, sub2.show_row, sub2.ord, sub2.sor_cost nulls last