我需要将A表中的几列求和放在B表中
A表
Date  
value1
value2B表
Month
sum1
sum2我写成insert B (Month,sum1,sum2) select Date, sum(value1), sum(value2) where Date between ...肯定不对
这个日期应该咋办呢?

解决方案 »

  1.   

    insert B (Month,sum1,sum2) select month(Date), sum(value1), sum(value2) where Date between ...
      

  2.   

    日期是主键,如果不写日期就没办法插入。我本来想写一个min(Date),但是同事说Month必须是该月的第一天,而Date不一定每天都有值,所以min不成。
      

  3.   

    DATEPART(mm,date)date 转换成month 
      

  4.   

    insert B (Month,sum1,sum2) 
       select month(Date), sum(value1), sum(value2) where Date between 'xx' and 'xx'
       group by  month(Date)
     
      

  5.   

    可不可以有个什么办法直接指定month的值,类似于这种
    insert B (Month,sum1,sum2) 
    select ‘2011-5-1’, sum(value1), sum(value2) where Date between 'xx' and 'xx'
    呵呵。
      

  6.   

    先把需求说清楚,如果按月汇总,可以这样。insert 表B (Month,sum1,sum2) 
    select 
          SUBSTRING(CONVERT(varchar(10),GETDATE(),120),1,7)+"_01" as MonthFristDay ,        
          Sum(value1) , Sum(value2)
    From A表
    Group By SUBSTRING(CONVERT(varchar(10),GETDATE(),120),1,7)先计算出月 SUBSTRING(CONVERT(varchar(10),GETDATE(),120),1,7) 
    再按月汇总
    再月上加1 SUBSTRING(CONVERT(varchar(10),GETDATE(),120),1,7) + '_01' 
      

  7.   

    对了,第一天要这么写SUBSTRING(CONVERT(varchar(10),GETDATE(),120),1,7)+'-01' as MonthFristDay 是一个减号,并且单引号
      

  8.   


    insert B (Month,sum1,sum2) 
       select convert(varchar(7),date,120)+'-01', sum(value1), sum(value2) where Date between 'xx' and 'xx'
       group by  convert(varchar(7),date,120)
     
    zheyanhg是你的要求了吧
      

  9.   

    大哥,报错。
    消息 164,级别 15,状态 1,第 1 行
    Each GROUP BY expression must contain at least one column that is not an outer reference.
    消息 207,级别 16,状态 1,第 17 行
    Invalid column name '_01'.
      

  10.   

    本帖最后由 roy_88 于 2011-05-20 16:40:48 编辑
      

  11.   

    不是跟你说了嘛,对了,第一天要这么写SUBSTRING(CONVERT(varchar(10),GETDATE(),120),1,7)+'-01' as MonthFristDay  是一个减号,并且单引号
      

  12.   

    insert B (Month,sum1,sum2) 
    select convert(varchar(8),Date,120)+'01' as date, sum(value1), sum(value2) 
    from table1
    where Date between ..... and ...
    group by convert(varchar(8),Date,120)
      

  13.   

    樓主按以上方法試試看
    --不需要這樣反復轉換
    SUBSTRING(CONVERT(varchar(10),GETDATE(),120),1,7)
      

  14.   


    Convert( varchar(7) , Date , 120 ) + '-01'这样第一天,比较简单