日期:2014-05-17 浏览次数:20694 次
--> 测试数据:[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([Carid] VARCHAR(1),[jydate] DATETIME,[jysl] INT,[jygls] INT) INSERT [tb] SELECT 'A','2012-06-02',30,1200 UNION ALL SELECT 'A','2012-06-12',35,1400 UNION ALL SELECT 'A','2012-06-22',32,1600 UNION ALL SELECT 'B','2012-06-02',34,1200 UNION ALL SELECT 'B','2012-06-24',33,1400 GO --> 测试语句: select a.Carid,convert(varchar(7),a.[min_jydate],120) as 月份, (sum_jysl-b.jysl)*100.0/(end_jygls-begin_jygls) as 平均油耗 from ( select Carid,min([jydate])as min_jydate,sum([jysl]) as sum_jysl ,min([jygls]) as begin_jygls ,max([jygls]) as end_jygls from tb group by Carid,convert(varchar(7),[jydate],120) ) a join tb as b on a.Carid=b.Carid and a.min_jydate=b.jydate /* Carid 月份 平均油耗 ----- ------- --------------------------------------- A 2012-06 16.750000000000 B 2012-06 16.500000000000 (2 行受影响) */