sql 2008 Study for three -----Merge

1.语法

 MERGE <tatget table> [AS <alias>]

USING 

(

<source query>

)

WHEN  {[NOT] MATCHED | <expression> THEN <action statement>  [<additional WHEN  clauses>,[.....n]}

2.实例 参考sqlserver2008 高级编程

创建一张累计销售表

create table sales.monthyrollup

(

year smallest not null,

month tinyint not null,

productid int not null foreign key references procudtion.product(productid),

qtysold int not null constraint pkyearmonthproductid primary key(year,month,product)

);


--查询当月第一天的数据

MERGE sales.monthlyrollup as smr

(

select soh.orderdate,sod.productid,sum(sod.orderqty)as qtysold from sales.salesorderheader soh

join sales.salesorderdetail sod on soh.salesorderid=sod.salesorderid

where soh.orderdate>='2003-08-01' and son.orderdate<'2003-08-02' 

group by soh.orderdate,sod,productid

)  as s

on (s.productid=smr.productid)--这里的on可以理解为if

when matched then 

update set smr.qtysold =smr.qtysold+s.qtysold 

when not matched then

insert (year,month,productid,qtysold) values(date part(yy,s.orderdate),date part(m,s.orderdate),s.productid,s.qtysold);


--查询当月第二天的数据

MERGE sales.monthlyrollup as smr

(

select soh.orderdate,sod.productid,sum(sod.orderqty)as qtysold from sales.salesorderheader soh

join sales.salesorderdetail sod on soh.salesorderid=sod.salesorderid

where soh.orderdate>='2003-08-02' and son.orderdate<'2003-08-03' 

group by soh.orderdate,sod,productid

)  as s

on (s.productid=smr.productid)

when matched then 

update set smr.qtysold =smr.qtysold+s.qtysold 

when not matched then

insert (year,month,productid,qtysold) values(date part(yy,s.orderdate),date part(m,s.orderdate),s.productid,s.qtysold);


会发现数据没有新增那么多,只是将在第一天没有的productid新增到里面,而有的产品id会直接累加。

这里可以新建作业,写成存储过程,每天晚上去更新表,第二天早上就可以得到所需的数据。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值