1

你能解释一下这些代码行的作用吗?

表 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提供了一种编写辅助语句以用于更大查询的方法,所以就像我声明一些我会使用的变量一样,但在那之后我有点困惑......以及为什么使用casefor get row and col; 另外为什么在这种情况下有两个: case when col+1>N then row+1 else,SQL怎么知道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
4

2 回答 2

2

可以忽略 table1 的列,因为只使用计数 - 因此您可以将 CTE 重写为:

;with coords(i,row,col,total,N) as (
    select 1, 1, 1, 10, 4
    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
    )
SELECT * FROM coords

...在SELECT * FROM coords那里可以可视化结果。

递归的select 1, 1, 1, 10, 4“种子” - 这是递归的后续级别将派生的行。其余的行是从(最初)作用于种子行的第二个查询构建的,然后是第二个查询的结果行反馈给自身,等等。

于 2011-05-16T23:02:21.403 回答
0

它正在创建一个common table expression.

它基本上是从select查询中创建一个临时表结构。选择语句正在执行以下操作:

1)在另一个语句中选择一组默认值1,1,1和一个计算N.N*(N.N+1)/2,最后从NN.N
2)中选择一个值。 3)第二个选择是用case语句做一些条件输出。UNIONselect

于 2011-05-16T22:46:13.147 回答