日期:2014-05-18  浏览次数:20617 次

这个SQL语句应该如何写?急等
表中有以下记录:

number   date
8             2007-01-01
4             2007-01-10
6             2007-01-10

6             2007-02-01
8             2007-02-02
4             2007-02-02
6             2007-02-03

7             2007-03-01


我想按月统计number的和跟当月的number的日均值,我想要的结果如下:

和     日均值     month
18     9               2007-01
24     8               2007-02
7       7               2007-03


注意:表中date是不唯一的,即有可能一天有多条记录

------解决方案--------------------
select sum(number),avg(number),convert(char(7),date,120) from table1 group by convert(char(7),date,120)
------解决方案--------------------
declare @t table(number int, [date] datetime)
insert @t
select 8, '2007-01-01 ' union all
select 4, '2007-01-10 ' union all
select 6, '2007-01-10 ' union all
select 6, '2007-02-01 ' union all
select 8, '2007-02-02 ' union all
select 4, '2007-02-02 ' union all
select 6, '2007-02-03 ' union all
select 7, '2007-03-01 '

select sum(number) as 和,
sum(number)/count(distinct [date]) as 日均值,
convert(varchar(7),[date],120) as [month]
from @t as a group by convert(varchar(7),[date],120)

/*结果
和 日均值 month
-------------------------------
18 9 2007-01
24 8 2007-02
7 7 2007-03
*/
------解决方案--------------------
select 和=sum(number),日均值=(sum(number)/count(distinct [date])),[month]=left([date],8) from [Table] group by left([date],8)
------解决方案--------------------
学习
------解决方案--------------------
create table t_sum(number int null,date datetime null)
insert into t_sum(number,date) select
8, '2007-01-01 ' union all select
4, '2007-01-10 ' union all select
6 , '2007-01-10 ' union all select

6, '2007-02-01 ' union all select
8, '2007-02-02 ' union all select
4, '2007-02-02 ' union all select
6 , '2007-02-03 ' union all select

7 , '2007-03-01 '

select a.sum,a.sum/b.c,a.c_date from


(select sum(t_a.number) as sum,t_a.c_date from

(select *,substring(convert(varchar(20),date,120),1,7) as c_date from t_sum)as t_a group by t_a.c_date) as a join
(

select t_b.c_date,count(date) as c from (select distinct date,substring(convert(varchar(20),date,120),1,7) as c_date from t_sum) as t_b group by t_b.c_date) as b
on a.c_date=b.c_date

drop table t_sum
------解决方案--------------------
以下語句在ACCESS中測試OK

Select
SUM(SUMnumber) As 和,
SUM(SUMnumber) / Count([date]) As 日均值,
Format(date, "yyyy-MM ") As [month]
From
(Select
SUM(number) As SUMnumber,
date
From