首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

怎么将单个查询结果逐个插入一张表

2013-02-19 
如何将单个查询结果逐个插入一张表?各位大师,我要生成一个4列三行的结果表。如下。其中的数值都要从底下的查

如何将单个查询结果逐个插入一张表?
各位大师,我要生成一个4列三行的结果表。如下。其中的数值都要从底下的查询里单独得出不能整行求出。请教如何逐个值把查询结果填入结果表。谢谢。


  时间段                   退回数    发货数  退回率
前3个月                  6                   100           6%
前8到9个月           7                    140          5%
24个月前               20                  200          10%


select count(distinct 序列号)--这个查出来是6
from Return
where time between 11月 and getdate() --这里不同

select count(distinct 序列号) --这个查出来是100
from Shipment
where time between 12月 and getdate()


select count(distinct 序列号)--这个查出来是7
from Return
where time between 前9 and 前8

select count(distinct 序列号) --这个查出来是140
from Shipment
where time between 前9 and 前8

[解决办法]

;with cte as(
select (
select count(distinct 序列号) from Return
where time between 11月 and getdate()
) 退回数,
(select count(distinct 序列号) from Shipment
where time between 12月 and getdate()
) 发货数
union all
select (
select count(distinct 序列号)from Return
where time between 前9 and 前8
),
(select count(distinct 序列号) from Shipment
where time between 前9 and 前8
)
union all...
)
select *,cast(退回数*100.0/发货数 as varchar(20))+'%' from cte


[解决办法]
自己按照结构建立一个表变量,然后插入数据初始化,最后慢慢更新。

热点排行