表示这样的
时间         设备1    设备2    设备3
2012-8-1       3        4         0
2012-8-2       0        6         0
2012-8-3       5        7         0
要求计算出八月份各个设备最大值-除了0以外的最小值,如果全是0如设备3那一列,max-min=0就行结果是
设备1    设备2    设备3
2           3        0

解决方案 »

  1.   


    declare @test table(时间 datetime, 设备1 int, 设备2 int, 设备3 int)
    insert into @test
    select '2012-8-1', 3, 4, 0 union all
    select '2012-8-2', 0, 6, 0 union all
    select '2012-8-3', 5, 7, 0
    select * from @testselect 设备1=max(设备1)-isnull(min(case when 设备1<>0 then 设备1 end),0),
       设备2=max(设备2)-isnull(min(case when 设备2<>0 then 设备2 end),0), 
           设备3=max(设备3)-isnull(min(case when 设备3<>0 then 设备3 end),0)
    from @test
    group by convert(varchar(7),时间,120)/*
    设备1         设备2         设备3
    ----------- ----------- -----------
    2           3           0
    */