一.WITH AS的含义
WITH AS短语,也叫做子查询部分(subquery factoring),可以让你做很多事情,定义一个SQL片断,该SQL片断会被整个SQL语句所用到。有的时候,是为了让SQL语句的可读性更高些,也有可能是在UNION ALL的不同部分,作为提供数据的部分。
特别对于UNION ALL比较有用。因为UNION ALL的每个部分可能相同,但是如果每个部分都去执行一遍的话,则成本太高,所以可以使用WITH AS短语,则只要执行一遍即可。如果WITH AS短语所定义的表名被调用两次以上,则优化器会自动将WITH AS短语所获取的数据放入一个TEMP表里,如果只是被调用一次,则不会。而提示materialize则是强制将WITH AS短语里的数据放入一个全局临时表里。很多查询通过这种方法都可以提高速度。
string data = @"SELECT '492494' rwd,'11' rq,'1' bl,'壹元整' md,'1' mr,'a' kx,'055fa99b-a932-4924-9430-71cf13bb6858' gid
UNION ALL SELECT '492494','1','1','壹元整','1','b','055fa99b-a932-4924-9430-71cf13bb6858'
UNION ALL SELECT '492494','1','1','壹元整1','1','c','055fa99b-a932-4924-9430-71cf13bb6858'"; string sql = string.Format("WITH K AS ( {0} ) update zab_RDType set Rdt_name=K.Un from K left join zab_RDType on K.Ui=Rdt_id", data);
with K as (
select ci_designerId,tb_diqu
,sum(case when ci_leixing=1 then (case when ci_sgYq=1 then ci_sgJinE else 0 end)+(case when ci_sjYq=1 then ci_sjJinE else 0 end)
else 0 end) bgM
,sum(case when ci_leixing=2 then (case when ci_sgYq=1 then ci_sgJinE else 0 end)+(case when ci_sjYq=1 then ci_sjJinE else 0 end)
else 0 end) cyM
,sum(case when ci_leixing=3 then (case when ci_sgYq=1 then ci_sgJinE else 0 end)+(case when ci_sjYq=1 then ci_sjJinE else 0 end)
else 0 end) syM
,sum(case when ci_leixing=4 then (case when ci_sgYq=1 then ci_sgJinE else 0 end)+(case when ci_sjYq=1 then ci_sjJinE else 0 end)
else 0 end) jdM
,sum(case when ci_leixing=5 then (case when ci_sgYq=1 then ci_sgJinE else 0 end)+(case when ci_sjYq=1 then ci_sjJinE else 0 end) else 0 end) qtM
,SUM((case when ci_sgYq=1 then ci_sgJinE else 0 end)+(case when ci_sjYq=1 then ci_sjJinE else 0 end)) zM
from zab_clientInfo where ci_state=7
group by ci_designerId,tb_diqu
) select u_id,u_xingMing,u_kaHao,u_quYu,bm_name,ISNULL(dq_id,0)dq_id,dq_name,ISNULL(zM,0)zM
,ISNULL(bgM,0)bgM,ISNULL(cyM,0)cyM,ISNULL(syM,0)syM,ISNULL(jdM,0)jdM,ISNULL(qtM,0)qtM
from zab_userList a
left join K on a.u_id=ci_designerId and a.tb_diqu=K.tb_diqu
left join zab_buMen b on bm_id=u_zuHao and b.tb_diqu=k.tb_diqu
left join zab_diQu on a.tb_diqu=dq_id
where u_zhuangtaiyg<>'离职' and u_id is not NULL
order by zm desc
结果: