插入数据如下图
这就是基础表了
--数值类型
select
cast(byint as nvarchar) as '数字',
SUM(value) as '值'
from test group by byint
union all select '合计',SUM(value) from test
--字符串类型
select
bychar as '字符串',
SUM(value) as '值'
from test group by bychar
union all select '合计',SUM(value) from test
--时间类型
select
cast(bytime as nvarchar) as '时间',
SUM(value) as '值'
from test group by bytime
union all select '合计',SUM(value) from test
结果如下图
因为每个汇总下面都加了一行合计,所以分类汇总字段需要转化为字符串类型,这样才不出错。
--时间类型日期
select
CONVERT(nvarchar(10),bytime,120) as '时间',
SUM(value) as '值'
from test group by CONVERT(nvarchar(10),bytime,120)
union all select '合计',SUM(value) from test
--时间类型日期二
select
CONVERT(nvarchar(10),bytime,120) as '时间',
(select SUM(value) from test t where CONVERT(nvarchar(10),t.bytime,120)=CONVERT(nvarchar(10),test.bytime,120)) as '值'
from test group by CONVERT(nvarchar(10),bytime,120)
union all select '合计',SUM(value) from test
--时间类型小时
select
cast(DATEPART(HH,bytime) as nvarchar) as '时间',
SUM(value) as '值'
from test group by DATEPART(HH,bytime)
union all select '合计',SUM(value) from test
结果如下图
第一段和第二段是根据时间的获取日期的函数来汇总信息的,大家看到结果是相同的。
那这两段有什么不同呢?
我们分别运行group by之前的语句,结果如下
第一段
第二段
第二段在没有group by的情况下,每个汇总行都给了一张表的信息,相当于聚合函数,只不过显示多条数据罢了。
第三段是根据时间的获取小时的函数来汇总信息的。
--自定义函数
if exists(select 1 from sysobjects where id=OBJECT_ID('getresult') and OBJECTPROPERTY(id,'IsInlineFunction')=0)
drop function getresult
go
create function getresult(@scode nvarchar(50)) returns nvarchar(50)
begin
declare @result nvarchar(50)
if @scode%2=1 set @result= '单数'
else if @scode%2=0 set @result= '双数'
else set @result= '其他'
return @result
end
go
select
dbo.getresult(byint) as '单双数',
SUM(value) as '值'
from test group by dbo.getresult(byint)
union all select '合计',SUM(value) from test
简单解释一下语句: