dati,a8,a10
2008-8-1,10,12
2008-8-2,11,13
2008-8-3,15,8
2008-8-4,8,4
计算表中的第一条记录与最后一条记录的a8,a10的差值
结果为
a8,a10
2,8能否用一条sql语句搞定?

解决方案 »

  1.   

    SELECT A8=MAX(A8)-MIN(A8),
    A10=MAX(A10)-MIN(A10)
     FROM TB
      

  2.   

    SELECT abs(a.a8-b.a8) [a8] , abs(a.a10-b.a10) [a10]
    from  (select  a8 ,a10 from  tb where  dati=(select max(dati) from tb) ) a , (select  a8 ,a10 from  tb where  dati=(select min(dati) from tb)) b
      

  3.   


    select a8=max(a.a8)-min(a.a8),a10=max(a.a10)-min(a.a10) from 
    (select top 2 a8,a10 from 表 order by a8) a
      

  4.   


    if object_id('表') is not null
       drop table 表
    create table 表
    ( dati datetime ,
      a8 int ,
      a10 int
    )
    insert into 表 select '2008-8-1',10,12
       union all   select '2008-8-2',11,13
       union all   select '2008-8-3',15,8
       union all   select '2008-8-4',8,4
    select a8=max(a.a8)-min(a.a8),a10=max(a.a10)-min(a.a10) from 
    (select top 2 a8,a10 from 表 order by a8) a
      

  5.   


    if object_id('t1') is not null
       drop table t1
    create table t1
    ( dati datetime ,
      a8 int ,
      a10 int
    )
    insert into t1 select '2008-8-1',10,12
       union all   select '2008-8-2',11,13
       union all   select '2008-8-3',15,8
       union all   select '2008-8-4',8,4
    select abs(sum(a8)) a1,abs(sum(a10)) a2 from (
    select a8,a10 from t1 where  dati <=all(select dati from t1)
    union all
    select -a8 a8,-a10 a10 from t1 where  dati >=all(select dati from t1)
    )t2
    /*
    a1          a2          
    ----------- ----------- 
    2           8(所影响的行数为 1 行)*/
      

  6.   

    如果dati列有重复需要再改一下
    select abs(sum(a8)) a8,abs(sum(a10)) a10 from (
    select top 1 a8,a10 from t1 where  dati <=all(select dati from t1)
    union all
    select top 1 -a8 a8,-a10 a10 from t1 where  dati >=all(select dati from t1)
    )t2
      

  7.   

    select a.a8-b.a8,a.a10-b.a10 from t a, t b where a.dati=(select max(dati) from t)
    and b.dati=(select min(dati) from t)