需要作出这么一张表 
                 id       date    buy     sell     stock
                  1      0101     0       200      7000
                  2      0101    300      0        7300
                  3      0101    0       100       7200
                         小计    300    300        7200                  6     0102     0       200      7000
                  7     0102     400      0        7400
                  8     0102     0       100       7300
                         小计    400    300        7300
  其中 小计中 统计“buy”、“sell”为累加,统计“stock”为分组中id最大的那个剩余值
  ID不一定连续,但有序并唯一。 
  select id, date, buy , sell, stock 
          from table_a
  union  
  (select '', ‘小计’,‘’, sum(buy), sum(sell), last(stock)
          from  table_a 
          group by date  )
  order by  date, id   
   
  关键是这个last(stock). 在sql server 中有没有相应的函数,若没有,用什么方法完成? 是自定义函数么? 不知道我说清楚了没,有没清楚的欢迎回帖问!多谢了

解决方案 »

  1.   

    select id, date, buy , sell, stock  
      from table_a
       union   
      (select '', ‘小计’,‘’, sum(buy), sum(sell),
        stock=(select top 1 stock from table_a where date=a.date order by id)
       from table_a a 
      group by date )
       order by date, id   
      

  2.   


    不是top 1 是要 last 
      

  3.   

    select top 1 stock from table_a where date=a.date order by id desc
    就是最后一个