SQL Server 2008 上的复杂查询
您能解释一下这几行代码的作用吗?
表 1:INT、VARCHAR、FLOAT
ID Name value
---------------------------
1 a1 32116580
2 a2 50785384
3 a3 54327508
4 a4 61030844
;with coords(i,row,col,total,N) as (
select 1,1,1,N.N*(N.N+1)/2, N.N
from (select count(*) N from table1) N
union all
select i+1,
case when col+1>N then row+1 else row end,
case when col+1>N then row+1 else col+1 end,
total, N
from coords
where i<total
)
我知道 with
提供了一种编写辅助语句以在较大查询中使用的方法,所以就像我声明一些变量一样使用,但之后我有点困惑......为什么使用 case
来获取 row 和 col
;另外为什么在这种情况下有两种情况: case when col+1>N then row+1 else
,SQL 如何知道何时执行一种情况或另一种情况
? ..
i row col total N
--------------------
1 1 1 10 4
2 1 2 10 4
3 1 3 10 4
4 1 4 10 4
5 2 2 10 4
6 2 3 10 4
7 2 4 10 4
8 3 3 10 4
9 3 4 10 4
10 4 4 10 4
Could you please explain what do these lines of code do?
Table 1: INT,VARCHAR,FLOAT
ID Name value
---------------------------
1 a1 32116580
2 a2 50785384
3 a3 54327508
4 a4 61030844
;with coords(i,row,col,total,N) as (
select 1,1,1,N.N*(N.N+1)/2, N.N
from (select count(*) N from table1) N
union all
select i+1,
case when col+1>N then row+1 else row end,
case when col+1>N then row+1 else col+1 end,
total, N
from coords
where i<total
)
I know with
provides a way to write auxiliary statements for use in a larger query, so it is like if I declare some variables I would use, but after that I am a little confused...And Why the use of case
for getting row and col
; Also why in the case there are two: case when col+1>N then row+1 else
, How does SQL know when to do one case or the other
?...
i row col total N
--------------------
1 1 1 10 4
2 1 2 10 4
3 1 3 10 4
4 1 4 10 4
5 2 2 10 4
6 2 3 10 4
7 2 4 10 4
8 3 3 10 4
9 3 4 10 4
10 4 4 10 4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以忽略 table1 的列,因为仅使用计数 - 因此您可以将 CTE 重写为:
...使用 SELECT * FROM coords 来可视化结果。
select 1, 1, 1, 10, 4
为递归“播种” - 这是从中导出后续级别的递归的行。其余的行是由作用于(最初)种子行的第二个查询构建的,然后第二个查询的结果行反馈到自身等。The columns of table1 can be ignored since only the count is being used - thus you can rewrite your CTE as:
...with a
SELECT * FROM coords
there to visualise the results.The
select 1, 1, 1, 10, 4
'seeds' the recursion - this is the row from which later levels of the recursion will derive. The rest of the rows are built up from the second query acting upon (initially) the seed row and then the resultant row from the second query fed back in to itself etc.它正在创建一个
公用表表达式
。它基本上是从其中的
select
查询创建一个临时表结构。 select 语句执行以下操作:1) 选择一堆默认值
1,1,1
和计算NN*(N.N+1)/2
和最后是来自N
表NN
的值
2) 在另一个
select
语句中使用UNION
。3)第二个select是用case语句做一些条件输出。
It is creating a
common table expression
.It is basically create a temporary table structure from the
select
query within. The select statement is doing the following:1) Selecting a bunch of default values
1,1,1
and a calculationN.N*(N.N+1)/2
and finally a value from theN
tableN.N
2)
UNION
ing in anotherselect
statement.3) The second select is doing some conditional output with the case statements.