我想编个小程序自己用,请大家帮我写个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
谢谢各位......
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
谢谢各位......
2、select 油罐号 损耗类型(1) 损耗类型(2) 损耗类型(3)
from 表名
where 油罐号='' group by 油罐号 损耗类型(1) 损耗类型(2) 损耗类型(3)试一下行么?
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
select 油罐号, max(日期) as 日期 from table group by 油罐号
2. select 油罐号,sum(损耗量) from 表A order by 油罐号 group by 损耗类型;
试试看,不行的话再改改。
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
naner_china(naner)
的方法正确!
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)
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 油罐号