不好意思写了不完整应该是:
create function mon(@year varchar(4))
returns table
as
return(select substring(buy_date,5,6)month,sum(num) number from book where substring(buy_date,1,4)=@year group by substring(buy_date,5,6))
go
例如:
表book
字段buy_date(买书日期 varchar(10)),num(买书数 int)
建一个函数
create function mon(@year varchar(4))
returns table
as
return(select sum(num) number from book where substring(buy_date,1,4)=@year group by substring(buy_date,5,6))
go
查询时比如查年的各个月的买书数量
select * from dbo.mon('2002')
select 1 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=1
union
select 2 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=2
union
select 3 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=3
union
select 4 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=4
union
select 5 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=5
union
select 6 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=6
union
select 7 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=7
union
select 8 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=8
union
select 9 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=9
union
select 10 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=10
union
select 11 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=11
union
select 12 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=12
select 1 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=1
union
select 2 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=2
union
select 3 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=3
union
select 4 as 买书月份, isnull(sum(买书数),0) as 买书数 from yourtable where year(买书日期) = 2000 and month(买书日期)=4