+ -
当前位置:首页 → 问答吧 → SQL里面用case when的问题。。。。

SQL里面用case when的问题。。。。

时间:2011-11-30

来源:互联网

我想搜索出b.GoodsId,b.Name,b.GuiGe,b.Unit,a.name,cost 这6列的数据,条件是在2个时间段内,就是BuyInfo表里面的DateOfBuy,我现在的问题是,cost这一列是变化的,我的GoodsInfo表里还有个字段是memo,我想通过memo的值来改变cost的这一列的算法,因为我的memo这一列只有2个值,比如是A和B,当memo的值是A的时候,cost这一列的算法就是cost=sum(Price*d.[count])/sum(d.[count]),当cost这一列的值是B时,就要先选择BuyInfo里面的DateOfBuy列,日期是过去30天到今天的数据,然后BuyDetails的BuyId是外键(和BuyInfo连接的),然后再在BuyDetails表里选择相应的Price和count列,来运算,算法还是一样的cost=sum(Price*d.[count])/sum(d.[count]),只是select的Price和count列给限制了而已。。。。说了这么多,不知道大家懂不懂我的意思。。。。一开始我是想用case when去写。。。但是不知道如何写。。。感觉限制的条件太多了。。有点混乱。。。。

这4张表:

Provider: ProId(供应商Id、主键)、Name(供应商名字)

GoodsInfo: GoodsId(商品id、主键)、Name(商品名称)、GuiGe(规格)、Unit(产地)、ProId(供应商Id、外键) 、memo

BuyInfo: BuyId(订单编号、主键)、ProId(供应商Id、外键)、DateOfBuy(采购日期、datetime类型)

BuyDetails: BuyId(订单编号、外键)、GoodsId(商品id、外键)、Count(数量)


作者: abcjunq   发布时间: 2011-11-30

搞几个数据上来 想要什么样子的结果等!

作者: yhui1989love   发布时间: 2011-11-30




解释得太混乱了。

作者: fredrickhu   发布时间: 2011-11-30

我先顶起来

作者: a1247449520   发布时间: 2011-11-30

SQL code

select b.GoodsId,
        b.Name,
        b,GuiGe,
        b.Unit,
        case memo when 'a' then sum(Price*d.[count])/sum(d.[count])  
                  when 'b' then  c.DateOfBuy 
        else set 'null' 
        end   as cost                                                        
from  Provider as a ,goodsInfo as b ,BuyInfo as c ,BuyDetails as d 
where  d.GoodsId=b.GoodsId and d.BuyId=c.BuyId and b.ProId=a.ProId and  DateOfBuy between '起始时间' and '结束时间'




大概的是这个意思?

作者: houyajin   发布时间: 2011-11-30



  最好能上点数据!

作者: abclm   发布时间: 2011-11-30

SQL code
--假设price是 GoodsInfo 表中的列
select b.GoodsId,b.Name,b.GuiGe,b.Unit,a.name,
cost=(select sum(c.Price*e.count)/sum(d.count)
 from goodsId c inner join buydetails d on c.goodsid=d.goodsid
inner join buyinfo e on d.buyid=e.buyid
where c.goodsid=b.goodsid and
datediff(d,e.dateofbuy,getdate())=(case when c.memo='A' then datediff(d,e.dateofbuy,getdate()) else 30 end))
from goodsinfo b inner join provider a on a.proid=b.proid

作者: qianjin036a   发布时间: 2011-11-30

e.count 换成 d.count

SQL code
--假设price是 GoodsInfo 表中的列
select b.GoodsId,b.Name,b.GuiGe,b.Unit,a.name,
cost=(select sum(c.Price*d.count)/sum(d.count)
 from goodsId c inner join buydetails d on c.goodsid=d.goodsid
inner join buyinfo e on d.buyid=e.buyid
where c.goodsid=b.goodsid and
datediff(d,e.dateofbuy,getdate())=(case when c.memo='A' then datediff(d,e.dateofbuy,getdate()) else 30 end))
from goodsinfo b inner join provider a on a.proid=b.proid

作者: qianjin036a   发布时间: 2011-11-30