表A ,a1,a2 字段 表B b1,b2 字段,其中,a1= b1
要写入另一个表(C)或者临时表,a1,b1字段相同,需要合并这样的报表需求,我们可以这么写:
首先把A表需要数据查出来写入 C表,c1,c2字段,然后再更新c3字段
存储过程:其中 A表是 T_ECert B表是 T_ECert2013 C表是临时表
CREATE PROCEDURE SP_RP_EcertReport1 --create by ChangChun for 统计全区从业人员总数
--@subOrgan varchar(1)
AS
BEGIN
SET NOCOUNT ON;
IF 1=0 BEGIN
SET FMTONLY OFF
END
CREATE TABLE #TMP (机构名称 varchar(100),旧版从业人员数量 INTEGER,新版从业人员数量 INTEGER);
DECLARE @organ VARCHAR(100),@ecertNum INTEGER,@ecert2013Num INTEGER;
DECLARE C1 CURSOR FOR SELECT DISTINCT SUBSTRING(convert(varchar(100),ziparea),1,4) FROM dbo.TB_Organ
OPEN C1
FETCH NEXT FROM C1 INTO @organ
WHILE @@fetch_status = 0
BEGIN
--先插入
INSERT INTO #TMP SELECT substring(convert(varchar(100),ziparea),1,4) as 区域编 码 ,count(*),0 as 旧版版从业证数量 from T_ECert
WHERE ECERTSTATE = ‘从业‘ and substring(convert(varchar(100),ziparea),1,4) = @organ
GROUP by substring(convert(varchar(100),ziparea),1,4) order by 区域编码;
--根据C表 更新 C3字段
UPDATE a SET a.新版从业人员数量 = b.新版从业证数量
FROM #TMP AS a,(SELECT substring(convert(varchar(100),ziparea),1,4) as 区域编 码 ,count(*) as 新版从业证数量 from T_ECert2013
WHERE ECERTSTATE = ‘从业‘ and substring(convert(varchar(100),ziparea),1,4) = @organ
GROUP by substring(convert(varchar(100),ziparea),1,4) ) AS b
WHERE a.机构名称 = b.区域编码
FETCH NEXT FROM C1 INTO @organ
END
CLOSE C1
DEALLOCATE C1
SELECT * FROM #TMP
END
本文出自 “数据领域” 博客,请务必保留此出处http://charlist.blog.51cto.com/1616209/1697383
原文地址:http://charlist.blog.51cto.com/1616209/1697383