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]

發佈了50 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章