我使用以下语句 (1) 统计每个物品在仓库的库存,但是在系统里面有些物品存会有一个基础库存,所以使用以下语句统计之后还要再搜索一下 建档库存表,检查当前物品是否已经存在基础库存,如果搜索为空或者为0则不需要相加,有则加上,以此来获得每个物品的库存,我想知道如何可以把(1) 和 (2) 语句合并以此来提升速度(1) SELECT theTypeName, SUM(CASE WHEN operation = '入货' THEN goodsnum ELSE - goodsnum END)  FROM ruhuo group by theTypeName(2)  Select nums from InitialTable where theTypeName='酱油' 

解决方案 »

  1.   

    SELECT theTypeName, SUM(CASE WHEN operation = '入货' THEN goodsnum ELSE - goodsnum END)  FROM ruhuo as a join InitialTable as b on a.theTypeName=b.theTypeName
    where b.theTypeName='酱油' 
    group by theTypeName 
      

  2.   

    SELECT theTypeName, 
    SUM(CASE WHEN operation = '入货' THEN goodsnum ELSE - goodsnum END) + 
    isnull((select nums from InitialTable where theTypeName=t.theTypeName),0) 
    FROM ruhuo 
    group by theTypeName t
      

  3.   

    似乎还有一一种写法是 SELECT theTypeName, SUM(CASE WHEN operation = '入货' THEN goodsnum ELSE - goodsnum END)  FROM ruhuo group by theTypeName 
    union all 
    Select theTypeName='酱油' , nums from InitialTable where theTypeName='酱油' 那么哪种在sql server 里面运行时最快的
      

  4.   


    group by theTypeName t ,意思 是 t是theTypeName 的缩写,并且where theTypeName=t.theTypeName那里表示等于正在统计的那个 theTypeName ?
      

  5.   

    写错。。SELECT theTypeName, 
    SUM(CASE WHEN operation = '入货' THEN goodsnum ELSE - goodsnum END) + 
    isnull((select nums from InitialTable where theTypeName=t.theTypeName),0) 
    FROM ruhuo t
    group by theTypeName 
    group by theTypeName t ,意思 是 t是theTypeName 的缩写,并且where theTypeName=t.theTypeName那里表示等于正在统计的那个 theTypeName ?
    [/Quote]
      

  6.   

    FROM ruhuo t他这里会自动判断当前正在统计的是哪个 theTypeName ?