了解自我与SQL Server中的函数联接

时间:2014-09-18 11:03:20

标签: sql-server self-join running-total

任何人都可以帮我理解我的查询吗?我知道这是正确的但不知何故我不知道我是如何得出这个结果的。

查询:

Select 
    A.Name, A.Age, SUM(B.Age) Running_Total
from 
    infoTbl  A, infoTbl B 
Where 
    A.Age <= B.Age 
Group By 
    A.Name, A.Age
Order By 
    A.Age Desc 

结果:

Name    Age   Running Total
---------------------------
A        25        25
B        20        45
C        18        63
D        15        78
E        1         79
F        5         84

的含义是什么?
Where A.Age <= B.Age
你能给我一个插图吗?非常感谢你。

2 个答案:

答案 0 :(得分:1)

让我们将您的查询分解为步骤

1

Select 
    A.Name, A.Age, b.Name as bName, B.Age as bAge
from 
    infoTbl  A, infoTbl B 
Where 
    A.Age <= B.Age 
Order By 
    A.Age desc, B.Age

相当于

Select 
    A.Name, A.Age, b.Name as bName, B.Age as bAge
from 
    infoTbl  A
    inner join infoTbl B on A.Age <= B.Age 
Order By 
    A.Age desc, B.Age

这将为您提供:对于表A中的每条记录,B中的记录具有相同的年龄或更高。

Name    Age   bName   bAge
---------------------------
A        25    A       25
B        20    B       20
B        20    A       25
C        18    C       18
C        18    B       20
C        18    A       25
...
etc...

当你现在按照你得到的数量添加总和时,是年龄等于年龄或年龄的人的总年龄

Select 
    A.Name, A.Age, SUM(B.Age) AS Running_Total
from 
    infoTbl  A
    inner join infoTbl B on A.Age <= B.Age
group by
    A.Name, A.Age 
Order By 
    A.Age desc



Name    Age   Running Total
---------------------------
A        25        25          (25)
B        20        45          (20 + 25 which is age of B+A)
C        18        63          (18 + 20 + 25 which is age of C+B+A)

答案 1 :(得分:0)

Where A.Age>=B.Age为您提供要添加的下一行。

您可以使用此代替自我加入

select *,sum(Age)over(order by Name) as Running_Total from table