SQL case when then 及 isnull() 例子

--> 测试数据:[动态表]
if object_id('[动态表]') is not null drop table [动态表]
go 
create table [动态表](id int,[日期] varchar(15),[原料ID] varchar(20),[原料名称] varchar(20),[成本单价] decimal(20,2))
insert [动态表]
select 1,'2013-11-01','00001','啤酒',10 union all
select 2,'2013-11-15','00001','啤酒',15 union all
select 3,'2013-11-02','00002','饮料',18 union all
select 4,'2013-11-03','00002','饮料',10 union all
select 5,'2013-11-08','00002','饮料',9 

--> 测试数据:[清单表]
if object_id('[清单表]') is not null drop table [清单表]
go 
create table [清单表]([原料ID] varchar(20),[原料名称] varchar(20),[成本单价] decimal(20,2),[期初单价] decimal(20,2))
insert [清单表]
select '00001','啤酒',10 ,15 union all
select '00002','饮料',9 ,18 union all
select '99999','红牛',0 ,20

--测试数据查看
select *

from [清单表] a left join 

(select [原料ID],[成本单价] from [动态表] where id in

(select max(id ) as id from [动态表] where[日期]<= '2013-11-15' group by [原料ID])

) b  on a.[原料ID]=b.[原料ID]
--结果数据 (15,9,20)
select a.[原料ID],a.[原料名称],case when a.[成本单价] <=0 then isnull(b.[成本单价],a.[期初单价]) 

else isnull(b.[成本单价],a.[成本单价]) end as [成本单价]

from [清单表] a left join 

(select [原料ID],[成本单价] from [动态表] where id in

(select max(id ) as id from [动态表] where[日期]<= '2013-11-15' group by [原料ID])

) b  on a.[原料ID]=b.[原料ID]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值