SQL資料庫CTE的用法

2021-05-21 22:07:50 字數 2758 閱讀 4766

在很多程式語言中都有 for迴圈這樣的東西。在資料庫裡面 替代他是 游標

但是游標使用起來是相當耗費資源的,今天看見乙個cte嘗試了下他的用法

create table employewhere

(id int identity(1,1),

[name] varchar(10),

[value] varchar(10),

[ttime] int

)insert employewhere

select '張三',2,1

union all

select '張三',2,2

union all

select '張三',2,3

union all

select '張三',2,4

union all

select '李四',2,1

union all

select '李四',2,2

union all

select '李四',2,3

union all

select '李四',2,4

union all

select '李四',2,1

insert employewhere

select '王五',2,1

union all

select '王五',2,3

union all

select '王五',2,4

我想得到ttime為連續數字的name

張三李四

select * from  employewhere

1 張三 2 1

2 張三 2 2

3 張三 2 3

4 張三 2 4

5 李四 2 1

6 李四 2 2

7 李四 2 3

8 李四 2 4

9 王五 2 1

10 王五 2 3

11 王五 2 4

12 王五 2 1

13 王五 2 3

14 王五 2 4

15 王五 2 1

16 王五 2 3

17 王五 2 4

with mycte as

(select id,[name],value,ttime ,1 as number   from employewhere where value=2

union all

select tt.id,tt.name,tt.value,tt.ttime ,number+1 from employewhere as tt

inner join mycte on mycte.[name]=tt.[name] and tt.ttime=mycte.ttime+1--連線起來的條件

where tt.value=2

)select * from mycte where number>3

8 李四 2 4 4

4 張三 2 4 4

但是為什麼要這麼寫呢

我們可以這麼執行查詢裡面的資料

with mycte as

(select id,[name],value,ttime ,1 as number   from employewhere where value=2

union all

select tt.id,tt.name,tt.value,tt.ttime ,number+1 from employewhere as tt

inner join mycte on mycte.[name]=tt.[name] and tt.ttime=mycte.ttime+1--連線起來的條件

where tt.value=2

)select * from mycte

可以得到資料

1 張三 2 1 1

2 張三 2 2 1

3 張三 2 3 1

4 張三 2 4 1

5 李四 2 1 1

6 李四 2 2 1

7 李四 2 3 1

8 李四 2 4 1

9 王五 2 1 1

10 王五 2 3 1

11 王五 2 4 1

12 王五 2 1 1

13 王五 2 3 1

14 王五 2 4 1

15 王五 2 1 1

16 王五 2 3 1

17 王五 2 4 1

11 王五 2 4 2

14 王五 2 4 2

17 王五 2 4 2

11 王五 2 4 2

14 王五 2 4 2

17 王五 2 4 2

11 王五 2 4 2

14 王五 2 4 2

17 王五 2 4 2

8 李四 2 4 2

7 李四 2 3 2

8 李四 2 4 3

6 李四 2 2 2

7 李四 2 3 3

8 李四 2 4 4

4 張三 2 4 2

3 張三 2 3 2

4 張三 2 4 3

2 張三 2 2 2

3 張三 2 3 3

4 張三 2 4 4

是不是發現很多重複資料 同時可以更直觀的讓我們認識 其實 cte本身就是乙個臨時表這樣的乙個東西 只是不要你進行建立

最後面一排 使我們寫的 number

然後我們在進行篩選

where number>3

就是排序中連續有三個的

於是就把 我們

張三和李四查詢出來了

SQL資料庫CTE的用法

在很多程式語言中都有 for迴圈這樣的東西。在資料庫裡面 替代他是 游標 但是游標使用起來是相當耗費資源的,今天看見乙個cte嘗試了下他的用法 create table employewhere id int identity 1,1 name varchar 10 value varchar 10...

資料庫之SQL 語句as的用法 SQL 結果重新命名

as 一般用在兩個地方,乙個是query的時候,用來重新指定返回的column 名字 如 乙個table 有個column叫 id,我們的query是 select id from table1.但是如果你不想叫id了,就可以重新命名,如叫 systemid 就可以這樣寫 select id as ...

SQL資料庫 管理資料庫

建立完資料庫,如何對它進行管理呢?管理資料庫包括對資料庫修改大小 新增資料檔案或日誌檔案 分離和附加資料庫等,同樣有語句和ssms兩種方法。接下來主要展示用sql語句方法更改,用介面的方式只需要在屬性裡更改就可以 將乙個新的事務日誌檔案xscjl log,初始大小100mb加入xscj中。alter...