聚合技术
select '表中的数据量'=Count(*),'表中的不为空的数据量'=Count(num1) from pv
count(*)为所有数据(包括空值)
count(num1)去掉空值后所有数据
这个只显示聚合值
Compute子句中的聚合
compute子句两种形式一种是不带by子句,一种是带by子句
select * from pv //明细值
compute sum(num1) //聚合值
go
既显示明细值又显示聚合值
这个是对所有的明细值算聚合值
select * from pv order by num1 desc ,num2 asc
comput sum(num1) by num1
既显示明细值又显示聚合值
这个是对by子句的要求对明细值分组,然后给出每一组的聚合值
by 后面跟order by 的顺序要一致
现在只能跟 by num1 或by num1,num2
分组技术
group by子句
select color ,'颜色相同的产品数量'=Count(*),'颜色相同的产品的最大安全库存量'=Max(safeystocklevel)
from product
where color is not null
group by color
having count(*) >10
第一步,执行from product子句,把表中的所有数据都检索出来。
第二步,执行where color is not null 子句,对上步中得到的数据进行过滤,过滤后的数据只包括那些有明确颜色的值的产品数据。
第三步,执行group by color子句,对上一步中的数据进行分组,计算每一组的统计数据和最大安全库存。
第四步,执行having count(*) >10子句,对上一步中的分组的数据进行过滤,只有产品数量超过10个的数据才能出现在最终的结果集中。
第五步,按照select子句指定的样式显示结果集。
Rollup和cube关键字
select itemName,color,'数量'=sum(quantity) from inventory
group by item,color with rollup
把color这列的所有颜色进行分组
样例:
itemName color 数量
汽车 红色 100
汽车 白色 100
汽车 绿色 100
汽车 null 300
这里null是所有的意思。
select itemName,color,'数量'=sum(quantity) from inventory
group by item,color with rollup
把item,color两列的所有颜色进行分组
汽车 绿色 100
汽车 null 100
自行车 白色 100
自行车 null 100
null 绿色 100
null 白色 100
null null 200
连接技术
交叉连接是返回两个表的乘积。
A表有5行数据,B表有6行数据,则结果集中有30行数据。
select id,name from a cross jion b
内连接是把两个表中的数据连接成生第三个表,在第三个表中,仅含那些满足连接条件的数据行。
select id ,name from a as aa inner join b as bb on aa.id=bb.id
外连接分为left outer join ,right outer join,full outer join
left outer join 是包括了左表中全部不满足的数据,对应另外一个表中的数据为null
select id ,name from a as aa left outer join b as bb on aa.id=bb.id
a是左表,b是右表
这里显示左表的所有数据,右表显示满足条件的数据。
right outer join 是包括了右表中全部不满足的数据,对应另外一个表中的数据为null
select id ,name from a as aa right outer join b as bb on aa.id=bb.id
a是左表,b是右表
这里显示右表的所有数据,左表显示满足条件的数据。
full outer join 是包括了
select id ,name from a as aa full outer join b as bb on aa.id=bb.id
a是左表,b是右表
这里显示左表的所有数据,右表显示所有数据。
集合运算技术
select * from a
union all //all显示全部数据,否则只显示唯一的数据
select * from b
显示 两个表中所有数据
select * from a //这里有123数据
except
select * from b //这里有2
显示表a中除表b中有的数据
这些表显示13数据
select * from a
intersect
select * from b
显示两个表的交集
公用表达式cte是定义在select、insert、update、delete语句中的临时命名的结果集。
with a(id ,name)
as
(
select id1,name1,Count(*) from aa
where name1 is not null
group by name1
)
select id,name from a oder by name