日期:2014-05-18 浏览次数:20521 次
if OBJECT_ID('test')is not null drop table test go create table test( 日期 date, 最高温度 int, 最低温度 int ) go insert test select '2012-01-01',7,-5 union all select '2012-01-02',6,-8 union all select '2012-01-03',6,-7 union all select '2012-01-04',8,0 union all select '2012-01-05',9,1 union all select '2012-02-01',12,2 union all select '2012-02-02',14,3 union all select '2012-02-03',10,1 union all select '2012-02-04',11,0 union all select '2012-02-05',13,2 union all select '2012-03-01',15,6 union all select '2012-03-02',17,8 union all select '2012-03-03',16,6 union all select '2012-03-04',14,5 select *, AVG(最高温度)over(partition by month(日期)) as 月平均最高温度, AVG(最低温度)over(partition by month(日期)) as 月平均最低温度 from test /* 日期 最高温度 最低温度 月平均最高温度 月平均最低温度 ------------------------------------ 2012-01-01 7 -5 7 -3 2012-01-02 6 -8 7 -3 2012-01-03 6 -7 7 -3 2012-01-04 8 0 7 -3 2012-01-05 9 1 7 -3 2012-02-01 12 2 12 1 2012-02-02 14 3 12 1 2012-02-03 10 1 12 1 2012-02-04 11 0 12 1 2012-02-05 13 2 12 1 2012-03-01 15 6 15 6 2012-03-02 17 8 15 6 2012-03-03 16 6 15 6 2012-03-04 14 5 15 6 */
------解决方案--------------------
create table test11 (dt datetime,high float,low float) insert into test11 values('2012-01-01',25.1,5.2) insert into test11 values('2012-01-03',35.1,5.2) insert into test11 values('2012-01-04',15.1,5.2) insert into test11 values('2012-01-05',25.1,11.2) insert into test11 values('2012-01-09',25.1,12.2) insert into test11 values('2012-02-01',35.1,13.2) insert into test11 values('2012-02-02',35.1,22.2) insert into test11 values('2012-02-03',25.1,18.2) insert into test11 values('2012-02-04',25.1,13.2) select CONVERT(char(7),dt,23),SUM(high)/COUNT(*),SUM(low)/COUNT(*) from test11 group by CONVERT(char(7),dt,23) select CONVERT(char(4),dt,23),SUM(high)/COUNT(*),SUM(low)/COUNT(*) from test11 group by CONVERT(char(4),dt,23) drop table test11
------解决方案--------------------
if OBJECT_ID('test')is not null drop table test go create table test( 日期 date, 最高温度 int, 最低温度 int ) go insert test select '2012-01-01',7,-5 union all select '2012-01-02',6,-8 union all select '2012-01-03',6,-7 union all select '2012-01-04',8,0 union all select '2012-01-05',9,1 union all select '2012-02-01',12,2 union all select '2012-02-02',14,3 union all select '2012-02-03',10,1 union all select '2012-02-04',11,0 union all select '2012-02-05',13,2 union all select '2012-03-01',15,6 union all select '2012-03-02',17,8 union all select '2012-03-03',16,6 union all select '2012-03-04',14,5 --SQL Server 2000 select *, (select AVG(最高温度) from test b where convert(varchar(7),a.日期,120)=convert(varchar(7),b.日期,120)) as 月平均最高温度, (sel