我想编个小程序自己用,请大家帮我写个SQL语句,数据库大致如下:日期(时间)      油罐号  油高   水高    重量   损耗类型  损耗量
2005-1-1         101     1.001  0.025  45000    1       50
2005-1-2         101     1.025  0.024  50000    2       60
2005-1-1         102     0.785  0.014  35000    1       70
2005-1-2         102     0.705  0.024  45000    1       85
2005-1-1         103     1.002  0.078  65000    1       80
2005-1-3         102     0.075  0.014  32000    2       90
2005-1-4         103     1.022  0.058  60000    3       1001、求每个油罐最后一个日期的数据,结果如下:
日期(时间)      油罐号  油高   水高    重量   
2005-1-2         101     1.025  0.024  50000
2005-1-3         102     0.075  0.014  32000
2005-1-4         103     1.022  0.058  600002、求按各个油罐的损耗类型分类汇总,结果如下:
油罐号    损耗类型(1)  损耗类型(2)  损耗类型(3)
101        50            60
102       155            90
103        80                           100
谢谢各位......

解决方案 »

  1.   

    1、select * from  表 where 油罐号='' and 时间='select max(时间) from 表 where 油罐号 = '''
    2、select 油罐号    损耗类型(1)  损耗类型(2)  损耗类型(3)
     from 表名 
     where 油罐号='' group by 油罐号    损耗类型(1)  损耗类型(2)  损耗类型(3)试一下行么?
      

  2.   

    select *
      from table1 x
     where 日期=(select max(日期) from table1 where 油罐号 = x.油罐号)
    select 油罐号,case 损耗类型 when 1 then 损耗量  else null end as 损耗类型1 ,
                  case 损耗类型 when 2 then 损耗量  else null end as 损耗类型2,
                  case 损耗类型 when 3 then 损耗量  else null  end as  损耗类型3
    from table1
      

  3.   

    1.
    select 油罐号, max(日期) as 日期 from table group by 油罐号
      

  4.   

    1. select  top(日期),油罐号,油高,水高,重量  from  表A  desc(日期) order bye  油罐号;
    2. select  油罐号,sum(损耗量) from 表A  order by 油罐号 group  by 损耗类型;
    试试看,不行的话再改改。
      

  5.   

    2.
    select 油罐号, sum(case 损耗类型 when 1 then 损耗量  else null) end as 损耗类型1 ,
                   sum(case 损耗类型 when 2 then 损耗量  else null) end as 损耗类型2,
                   sum(case 损耗类型 when 3 then 损耗量  else null)  end as  损耗类型3
    from table
      

  6.   

    经过判断
    naner_china(naner)
    的方法正确!
      

  7.   

    时间不能直接max,需要转换一下格式的吧,formate一下,楼上的兄弟们。
      

  8.   

    select * from biao x where 日期 in (select max(日期) fff from biao c where x.油罐号=c.油罐号 ) order by 油罐号
      

  9.   

    第二题实在想不出更快的方法来
    create table xxx(ygh varchar(20),shlx varchar(10),shl int) --创建临时表
    insert into xxx select 油罐号,损耗类型,sum(损耗量) from aaa group by 油罐号,损耗类型declare @sql varchar(4000)
    set @sql = 'select ygh'
    select @sql = @sql + ',sum(case shlx when '+shlx+' then shl end) ['+shlx+']'
     from (select distinct shlx from xxx) as a
    select @sql = @sql+' from xxx group by ygh'
    exec(@sql)
      

  10.   

    select *
      from table1 x
     where 日期=(select max(日期) from table1 where 油罐号 = x.油罐号)第二道题有点问题
    修改如下
    select a.油罐号, sum(case a.损耗类型 when 1 then 损耗量  else null end) as 损耗类型1 ,
                   sum(case a.损耗类型 when 2 then 损耗量  else null end) as 损耗类型2,
                   sum(case a.损耗类型 when 3 then 损耗量  else null end)  as  损耗类型3
    from table1 a group by 油罐号