如何将 table SQL ORACLE table 与特定行分组
How to group table SQL ORACLE table with specific rows also present
我有 table 这样的:
Area | Client | Month
a | A | 1
a | B | 1
b | C | 1
a | A | 2
b | B | 2
我如何分组和汇总此 table,以实现如下结果:
Area | Client | Month | Count
a | A | 1 | 1
a | B | 1 | 1
a | | 1 | 2
b | C | 1 | 1
b | | 1 | 1
| | 1 | 3
a | A | 2 | 1
a | B | 2 | 1
a | | 2 | 2
| | 2 | 2
| | | 5
我想按地区和月份计算客户数量,但还要列出客户列。我很难在存在客户列的情况下使用 "group by"。
我也想 "order by" 个月,但摘要也正确排序。
Oracle 已经有 rollup and cube grouping functions 用于此类查询,请使用:
select area, client , month, sum(month) count
from mytable
group by rollup(area, client,month)
order by area, client;
或者,这将产生小计的小计:
select area, client , month, sum(month) count
from mytable
group by cube(area, client,month)
order by area, client, month;
比起cube
或rollup
,我更喜欢grouping sets
,因为它更灵活。
然而,使用它们的关键是你需要一个聚合。所以,我想你想要 第四 列:
select area, client, month, count(*) as cnt
from t
group by grouping sets ( (area, client, month), (area, month), (month));
我有 table 这样的:
Area | Client | Month
a | A | 1
a | B | 1
b | C | 1
a | A | 2
b | B | 2
我如何分组和汇总此 table,以实现如下结果:
Area | Client | Month | Count
a | A | 1 | 1
a | B | 1 | 1
a | | 1 | 2
b | C | 1 | 1
b | | 1 | 1
| | 1 | 3
a | A | 2 | 1
a | B | 2 | 1
a | | 2 | 2
| | 2 | 2
| | | 5
我想按地区和月份计算客户数量,但还要列出客户列。我很难在存在客户列的情况下使用 "group by"。 我也想 "order by" 个月,但摘要也正确排序。
Oracle 已经有 rollup and cube grouping functions 用于此类查询,请使用:
select area, client , month, sum(month) count
from mytable
group by rollup(area, client,month)
order by area, client;
或者,这将产生小计的小计:
select area, client , month, sum(month) count
from mytable
group by cube(area, client,month)
order by area, client, month;
比起cube
或rollup
,我更喜欢grouping sets
,因为它更灵活。
然而,使用它们的关键是你需要一个聚合。所以,我想你想要 第四 列:
select area, client, month, count(*) as cnt
from t
group by grouping sets ( (area, client, month), (area, month), (month));