公用表表示式CTE

2021-09-06 18:22:45 字數 1788 閱讀 3722

公用表表示式cte表面上和派生表非常相似,看起來只是語義上的區別。但和派生表比較起來,cte具有幾個優勢:第一,如果須要在乙個cte中引用另乙個cte,不需要像派生表那樣巢狀,相反,只要簡單地在同乙個with子句中定義多個cte,並用逗號把它們分隔開。每個cte可以引用在它前面定義的所有cte。而外部查詢可以引用所有cte。

下面是乙個公用表表示式cte的示例。

use

tsqlfundamentals2008;

go--

公用表表示式cte

--乙個簡單的公用表表示式的例子

with usacusts as

(

select custid,companyname from

sales.customers

where country= n'

usa'

)select

*from

usacusts;

--分配列別名

with c as

(

select

year(orderdate) as orderyear,custid from

sales.orders

)select orderyear, count(distinct custid) from

cgroup

byorderyear;

--使用引數

declare

@empid

asint=3

;with c as

(

select

year(orderdate) as orderyear,custid from

sales.orders

where empid=

@empid

)select orderyear, count(distinct

custid)

from

cgroup

byorderyear;

--定義多個cte

with c1 as

(

select

year(orderdate) as orderyear, custid from

sales.orders

),c2 as(

select orderyear,count(distinct custid) as numcusts from

c1

group

byorderyear

)select orderyear,numcusts from

c2where numcusts>70;

--cte的多引用

with yearlycount as

(

select

year(orderdate) as orderyear, count(distinct custid) as numcusts from

sales.orders

group

byyear

(orderdate)

)select cur.orderyear, cur.numcusts as curnumcusts,prv.numcusts as prvnumcusts,cur.numcusts-prv.numcusts as

growth

from yearlycount as

curleft

join yearlycount as prv on cur.orderyear = prv.orderyear+

1;

公用表表示式 CTE

在編寫t sql 時,往往需要臨時儲存某些結果集。前面我們已經廣泛使用和介紹了兩種臨時儲存結果集的方法 臨時表和表變數。除此之外,還可以使用公用表表示式的方法。公用表表示式 common table expression 是sql server2005版本的引入的乙個特性。cte可以看組是乙個臨時的...

公用表表示式 CTE

在編寫t sql 時,往往需要臨時儲存某些結果集。前面我們已經廣泛使用和介紹了兩種臨時儲存結果集的方法 臨時表和表變數。除此之外,還可以使用公用表表示式的方法。公用表表示式 common table expression 是sql server2005版本的引入的乙個特性。cte可以看組是乙個臨時的...

公用表表示式 CTE

下面看在cte中分配列別名的兩種格式 內聯格式和外部格式。內聯格式 1 with c as2 3select year orderdate as orderyear,custid 4from sales.orders5 6select orderyear,count distinct custid ...