select GoosID '编号',sum(gsnum) '本月结存',gyear+'-'+gmonth as '时间' from GoodsRecord where goosid='A001' group by goosid,gyear+'-'+gmonth
(就改这个语句)
我要查出来得效果是
编号  本月结存  时间
A001   100     2008-12
A001   100     2009-02
A001   100     2009-03

字段有GoosID  --编号
       Gyear  --年
      Gmonth  --月
      Gday    --日
      Ginput  --进
      Goutput  --销
      Gexit    --存
      GSnum    --当天结存(和当时得库存吻合)
但现在得问题是本月结存sum(gsnum) 应该不是这个月‘当天结存’总和 我建得表应该是这个月最后一次活动得结存为这个月得本月结存 如A商品2月1号结存100 2月22号结存55 A商品22号后这个月就没卖出东西了 A商品2009-02结存55
本年本月结存多少我写出来了 但是其他得不会了
select GoosID '编号',sum(gsnum) '本月结存' from GoodsRecord where gyear='" + DateTime.Now.ToString("yyyy") + "' and gmonth='" + DateTime.Now.ToString("MM") + "' and gday in (select max(cast(gday as int)) from GoodsRecord where gyear='" + DateTime.Now.ToString("yyyy") + "' and gmonth='" + DateTime.Now.ToString("MM") + "' group by goosid) group by goosid用最上面我写得语句查出来的都是一个月当天结存得总和 大家帮我改下呀 效果就是 某商品某年某月结存多少

解决方案 »

  1.   

    select GoosID '编号',sum(gsnum) '本月结存' ,Gyear+Gmonth as 时间 
    from GoodsRecord 
    where 你需要的日期范围
    group by goosid,Gyear+Gmonth
      

  2.   

    试试group by子句后面的"gyear+'-'+gmonth"改为"gyear,gmonth",但是我感觉你的表字段设计有问题,应该有一个datatime型字段就可以包含年月日了,如果你要取得其中的
    年和月,只要用datepart函数或者用convert转换成你要的字符格式就行了。根据你的意思我写了个小测试,
    create table #goods
    (
        goodsid nchar(10),
        counts  int,
        years int,
        months int    
    )
    insert into #goods values('A001',100,2008,12)
    INSERT INTO #GOODS VALUES('A001',50,2008,12)
    INSERT INTO #GOODS VALUES('A002',100,2008,12)
    INSERT INTO #GOODS VALUES('A001',100,2009,1)
    INSERT INTO #GOODS VALUES('A001',100,2009,2)SELECT GOODSID,SUM(COUNTS)AS SUMCOUNT,(CAST(YEARS AS NCHAR(4)) + '-' + CAST(MONTHS AS NCHAR(2))) as time 
    FROM #GOODS
    where GOODSID='A001' 
    GROUP BY GOODSID,YEARS,MONTHS
    DROP TABLE #GOODS----------------result----------------
    goodid          counts  time
    A001       100 2009-1 
    A001       100 2009-2 
    A001       150 2008-12
      

  3.   

    写出来了
    select GoosID '编号',sum(gsnum) '本月结存',gyear+'-'+gmonth as '时间' from GoodsRecord 
    where goosid='BBBBB' and gday in 
    (select max(cast(gday as int)) from goodsrecord 
    where goosid='BBBBB' group by gyear,gmonth) 
    group by goosid,gyear+'-'+gmonth
    谢谢你们帮忙呀 2个人 刚好对半分