(8) SELECT (9) DISTINCT (11) <TOP_specification> <select_list>
(1) FROM <left_table>
(3) <join_type> JOIN <right_table>
(2) ON <join_condition>
(4) WHERE <where_condition>
(5) GROUP BY <group_by_list>
(6) WITH {CUBE | ROLLUP}
(7) HAVING <having_condition>
(10) ORDER BY <order_by_list>
要点:
第一:执行顺序,每个执行从句生成一个查询者不可见的事实表,执行顺序如序号所示。
第二:with{cube|rollup}的应用:
group、grouping、rollup、cube的用法和区别
--创建测试表
if exists(select name from sysobjects where name=N'test' and type='U')
DROP TABLE test
create table test(id int,sort char(10),color char(10),num int constraint pk_test primary key(id,sort,color))
--插入数据
insert into test
select 1,'book','blue',10
union all
select 1,'book','green',10
union all
select 1,'book','red',10
union all
select 1,'car','blue',10
union all
select 1,'car','red',10
union all
select 2,'car','red',10
--group by
select sort,color,sum(num) as num from test group by sort,color
--输出结果
--book blue 10
--car blue 10
--book green 10
--book red 10
--car red 20
--group by with rollup
select
case
when grouping(sort)=1 then 'all'
else isnull(sort,'unknow')
end as sort,
case
when grouping(color)=1 then 'all'
else isnull(color,'unknow')
end as color,
sum(num) as num from test
group by sort,color with rollup
--输出结果
--book blue 10
--book green 10
--book red 10
--book all 30
--car blue 10
--car red 20
--car all 30
--all all 60
--group by with cube
select
case
when grouping(sort)=1 then 'all'
else isnull(sort,'unknow')
end as sort,
case
when grouping(color)=1 then 'all'
else isnull(color,'unknow')
end as color,
sum(num) as num from test
group by sort,color with cube
--输出结果
--book blue 10
--book green 10
--book red 10
--book all 30
--car blue 10
--car red 20
--car all 30
--all all 60
--all blue 20
--all green 10
--all red 30
总结:
1、CUBE 和ROLLUP 之间的区别在于:
• CUBE 生成的结果集显示了所选列中值的所有组合的聚合。
• ROLLUP 生成的结果集显示了所选列中值的某一层次结构的聚合。
2、GROUPING是一个聚合函数,它产生一个附加的列,当用CUBE 或ROLLUP 运算符添加行时,附加的列输出值为,当所添加的行不是由CUBE 或ROLLUP 产生时,附加列值为。
仅在与包含CUBE 或ROLLUP 运算符的GROUP BY 子句相联系的选择列表中才允许分组。