正确关联sql查询

时间:2012-02-15 12:40:08

标签: sql-server-2005

Salary  Sum
10       10
20       30
10       40
70       110

我需要一个查询,它给出了上述格式的数据表,其中sum列的值取决于工资列

1 个答案:

答案 0 :(得分:0)

如果您的表中有主键,则可以使用以下内容:

DECLARE @tbl TABLE(ID INT,Salary INT)
INSERT INTO @tbl
VALUES
    (1,10),
    (2,20),
    (3,10),
    (4,70)

SELECT
    tbl.Salary,
    SUM(tbl2.Salary) AS [Sum]
FROM
    @tbl AS tbl
    JOIN @tbl AS tbl2
        ON (tbl2.ID <= tbl.ID)
GROUP BY 
    tbl.ID,
    tbl.Salary
ORDER BY 
    tbl.ID,
    tbl.Salary