34,590
社区成员
发帖
与我相关
我的任务
分享
[Quote=引用楼主 kyle2cj 的帖子:]
Month fee
20090112 10
20090123 20
20090203 15
20090227 16
20090301 11
怎么样写查询语句得到:按Month对Fee求和
Month fee
200901 30
200902 31
200903 11
[/Quote]
create table tb([Month] datetime, fee int)
insert into tb values('20090112' , 10 )
insert into tb values('20090123' , 20 )
insert into tb values('20090203' , 15 )
insert into tb values('20090227' , 16 )
insert into tb values('20090301' , 11 )
go
select convert(varchar(6),[month],112) [Month],sum(fee) fee
from tb
group by convert(varchar(6),[month],112)
order by [Month]
drop table tb
Month fee
------ -----------
200901 30
200902 31
200903 11
(3 行受影响)
create table tb([Month] datetime, fee int)
insert into tb values('20090112' , 10 )
insert into tb values('20090123' , 20 )
insert into tb values('20090203' , 15 )
insert into tb values('20090227' , 16 )
insert into tb values('20090301' , 11 )
go
select convert(varchar(6),[month],112) [month], sum(fee) fee from tb group by convert(varchar(6),[month],112)
drop table tb
/*
month fee
---------- -----------
200901 30
200902 31
200903 11
(所影响的行数为 3 行)
*/
create table tb([Month] varchar(10), fee int)
insert into tb values('20090112' , 10 )
insert into tb values('20090123' , 20 )
insert into tb values('20090203' , 15 )
insert into tb values('20090227' , 16 )
insert into tb values('20090301' , 11 )
go
select left([month],6) [month] , sum(fee) fee from tb group by left([month],6)
drop table tb
/*
month fee
---------- -----------
200901 30
200902 31
200903 11
(所影响的行数为 3 行)
*/
select left(month,6) as Month,sum(fee) as fee from tb group by left(month,6)
select left([month],6) [month] , sum(fee) fee from tb group by left([month],6)
DECLARE @TB TABLE(Month VARCHAR(8), fee INT)
INSERT @TB
SELECT '20090112', 10 UNION ALL
SELECT '20090123', 20 UNION ALL
SELECT '20090203', 15 UNION ALL
SELECT '20090227', 16 UNION ALL
SELECT '20090301', 11
SELECT LEFT(MONTH,6) AS [MONTH],SUM(FEE) AS FEE
FROM @TB
GROUP BY LEFT(MONTH,6)
/*
MONTH FEE
-------- -----------
200901 30
200902 31
200903 11
*/