易截截图软件、单文件、免安装、纯绿色、仅160KB

SQL数据库CTE的用法

在很多编程语言中都有 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


相关文档:

SQL时间比较 dateDiff方法使用

DateDiff
  DateDiff: SQL server函数
  返回 Variant (Long) 的值,表示两个指定日期间的时间间隔数目。
  语法
  DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])
  DateDiff 函数语法中有下列命名参数:
  部分 描述
  interval 必要。字符串表达式,表示用来计算date1 ......

SQL 初级教程

是用于访问和处理数据库的标准的计算机语言。
通过 SQL 来管理数据
结构化查询语言 (SQL) 是用于访问数据库的标准语言,这些数据库包括 SQL Server、Oracle、MySQL、Sybase 以及 Access 等等。
对于那些希望在数据库中存储数据并从中获取数据的人来说,SQL 的知识是价值无法衡量的。
什么是 SQL?
SQL 指结构化查询语言 ......

sql server创建表

use test
go
if exists table student is not null
else
drop table student
go
create table  database_name.schema_name.table_name
(属性1  字符类型  约束,
属性2  字符类型  约束....
)
go
insert into table_name values ('属性1’,‘属性2’,......)
--插 ......

SQL日期时间不能早于1753年

SQL日期时间不能早于1753年
   
1.公元元年的第一天,也就是公元1年1月1日,那天是星期六。
    2.
现行的公历是格利戈里历法,这个历法并不是连续的,中间缺少了11天。1752年9月2日的后一天并不是9月3日,而是9月14日。也就是说,从1752年9月3日到9月13日的11天并不存在。
 &nb ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号