表话费A ,年月,金额
求 left(年月,4)即该年的话费平均值例如:
2009-01 50
2009-02 100
2009-03 200
2009-04 50
2009-05 100。select left(年月,4),avg(金额) from A group by 年月最后出来很多记录,而不是一条记录
求 left(年月,4)即该年的话费平均值例如:
2009-01 50
2009-02 100
2009-03 200
2009-04 50
2009-05 100。select left(年月,4),avg(金额) from A group by 年月最后出来很多记录,而不是一条记录
--> 测试时间:2009-07-08 10:59:07
--> 我的淘宝: http://shop36766744.taobao.com/if object_id('[tab]') is not null drop table [tab]
create table [tab]([A] varchar(7),[B] int)
insert [tab]
select '2009-01',50 union all
select '2009-02',100 union all
select '2009-03',200 union all
select '2009-04',50 union all
select '2009-05',100select left(A,4),avg(B) from [tab] group by left(A,4)
/*
------- -----------
2009 100(所影响的行数为 1 行)*/drop table tab
---------------------------------
-- Author: htl258(Tony)
-- Date : 2009-07-08 10:57:47
---------------------------------
--> 生成测试数据表-tbif not object_id('tb') is null
drop table tb
Go
Create table tb([年月] nvarchar(7),[金额] int)
Insert tb
select '2009-01',50 union all
select '2009-02',100 union all
select '2009-03',200 union all
select '2009-04',50 union all
select '2009-05',100
Go
--Select * from tb-->SQL查询如下:
select left(年月,4),avg(金额) from tb group by left(年月,4)
/*
---- -----------
2009 100(1 行受影响)*/
select left(年月,4),avg(金额) from A group by 年月
where 年月='2009-04'
看错了,我以为你要查4月的呢。
select left(年月,4),avg(金额) from A group by 年月 如果是这样的话,会将
2009-01
2009-02
2009-03
看着一组,所以查出来有很多记录。后面分组问题!
将 left(年月,4) 放到 group by 即可!
SQL 提示:不能group by left(年月,4),只能 group by 年月,为何?
from A
where 部门 like @lb+'%'
group by 部门,left(工作年月,4)
from A
where 部门 like @lb+'%'
group by 部门,left(工作年月,4)
from A
where 部门 like @lb+'%'
group by 部门,left(工作年月,4)
drop table tb
Go
if object_id('A') is not null drop table A
go
create table A([工作年月] varchar(7),部门 varchar(10),金额 int)
insert A
select '2009-01','a',50 union all
select '2009-02','a',100 union all
select '2009-02','a',100 union all
select '2009-03','a',200 union all
select '2009-04','a',50 union all
select '2009-05','a',100SELECT left(工作年月,4)+'年' 年份,部门,avg(金额) 平均金额
from A
where 部门 like 'a'+'%'
group by 部门,left(工作年月,4)
/*
年份 部门 平均金额
--------- ---------- -----------
2009年 a 100(1 行受影响)
*/
from A
where 部门 like 'a'+'%'
group by 部门,left(工作年月,4)怪了,为何我这里执行报错呢?
我将+'年'去了,就行了。
即:
SELECT left(工作年月,4) 年份,部门,avg(金额) 平均金额
from A
where 部门 like 'a'+'%'
group by 部门,left(工作年月,4)真是怪了,与设置有关。