日期:2014-05-17  浏览次数:20694 次

求一sql语句??
一数据表格:
  Carid(车辆id) jydate(加油日期) jysl(加油数量) jygls(加油公里数)
A 2012-06-02 30 1200
A 2012-06-12 35 1400
A 2012-06-22 32 1600
B 2012-06-02 34 1200  
B 2012-06-24 33 1400
按照carid 加油月份 加油数量 加油公里数 平均油耗 显示:
 其中平均油耗为(月份加油数合计-按日期该月第一次加油数量)×100/加油公里数之差
比如A车六月份油耗为(35+32)*100/(1600-1200),sql语句如何实现?


------解决方案--------------------
SQL code
--> 测试数据:[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 行受影响)


*/