关于SQL 的with as 循环用法
来源:互联网 发布:java认证考试一年几次 编辑:程序博客网 时间:2024/05/22 09:28
WITH AS短语也叫做子查询部分(subquery factoring),是用来定义一个SQL片断,该SQL片断会被整个SQL语句所用到。这个语句算是公用表表达式(CTE),对于with 的循环 sql 2008有限制,最大只能递归 100 次,下面来测试看看。
如我想生成1到200行的数据
代码:with t as (
select 1 as id
union all
select t.id+1 from t where t.id<200)
select * from t
运行时报错:,对于CTE的限制需要利用recursion 函数解除限制,
with t as (
select 1 as id
union all
select t.id+1 from t where t.id<200)
select * from t
option (maxrecursion 0) 这样执行就没有问题,0是代表无限大,也可以改1000,或者2000 指定的数值,前提是要大于你递归的次数,不然还是报错。再来说说利用with 自定义值去循环指定值,下面拿做的一个SSRS 报表进行演示,excel效果图如下,现在要作成SSRS 报表。
第一:将出勤人员的姓名与(出勤、上班、下班)做循环,再取出刷卡时间。
with x as ------------定义循环值
(select * from (values(N'出勤'),
(N'上班'),
(N'下班'))as a (type1)),
y as (select distinct a.userid,b.name,b.BADGENUMBER
from 出勤table a
inner join usertable b on a.USERID = b.USERID,
z as (select * from x,y)
select * from z 结果
可以看到出勤、上班、下班 三个值已经跟每个user进行了循环,
第二 :再自定义指定某年的某月存在的日期天数
代码如:date1 as
(select convert(varchar(10),dateadd(DAY,t2.number,t1.day),120) day from
(select @date1+'-'+@date2+'-01' day) t1,
(select number from MASTER..spt_values WHERE TYPE='P' AND number>=0 and number<=31) t2
where convert(varchar(10),dateadd(DAY,t2.number,t1.day),120) like @date1+'-'+@date2+'%'
)-----------@date1 为指定的年份、@date2 为指定的月份,当然需要在前面定义变量值,这里就省略了,
第三:再将打卡时间进行排名,在http://blog.csdn.net/qyx0714/article/details/72683408 这里介绍按打卡时间排名取打卡数据的介绍,最终整理SSRS 图如下:
- 关于SQL 的with as 循环用法
- SQL WITH AS的用法
- SQL - WITH AS 用法
- sql with as 用法
- sql with as 用法
- sql with as 用法
- sql with as 用法
- sql with as 用法
- sql with as 用法
- sql with as 用法
- SQL - WITH AS 用法
- sql with as 用法
- sql with as 用法
- sql with as 用法
- sql with as 用法
- sql with as 用法
- sql with as 用法
- sql with as 用法
- EventBus使用详解(二)——EventBus使用进阶
- 练习96
- list.h
- html5获取地理位置和定位
- opencv,视频的操作
- 关于SQL 的with as 循环用法
- 改变文字大小
- JS 日历
- ubuntu16.10 docker 配置ngixn + php7 + mysql
- Nginx配置文件详解(nginx.conf)
- android集成谷歌地图
- Luban—— Android图片压缩工具
- 配置Keepalived实现Mysql双主高可用配置(完整配置)
- C++运算符重载