日期:2014-05-17  浏览次数:20763 次

一个SQL语句中的条件
本帖最后由 yaotomo 于 2013-08-14 09:35:57 编辑
n_dryweight字段可能有负值,当遇到负值时都按0计算。c_sw04字段可能不空,当不空时不进行sum


select  s.c_materialid 物料编码,
               case
                 when sum(s.n_dryweight) > 0 and s.c_sw04 is null then
                   sum(s.n_dryweight)       
                 else
                  0
               end 当日库存
          from AG_TP_STOCK s
          left join TB_MATERIELMAIN b
            on b.c_materielid = s.c_materialid
         where s.c_storageid = '20802079'
           and b.c_factoryid = '2080'
         group by s.c_materialid


如果我把条件c_sw04 is null写到where条件里,就无法得到那些c_sw04字段为空的物料编码。我想得到所有的物料编码,如果这个物料的c_sw04字段有值,库存就为0。

UNION的方法我也试过,虽然可以实现,但是效率太低,慢的要死。。。
如果按我上面的写法,就会提示s.c_sw04 is null不是group by 表达式。。。我该怎么写才能实现这个查询啊。。。

因为这个查询还要和其他查询做链接,所以必须得到所有的物料编码才可以。

------解决方案--------------------
不好意思,上面的应该有点问题

select  s.c_materialid 物料编码,
               sum (case
                 when s.n_dryweight> 0 and s.c_sw04 is null then s.n_dryweight      
                 else 0  end ) 当日库存