|
[code=sql]USE tempdb
IF OBJECT_ID('TEST') IS NOT NULL
DROP TABLE TEST; -->如果表TEST不为空,删除表
GO
CREATE TABLE TEST -->创建测试表,字段及类型如下
(
id int,
num int
);
GO
INSERT INTO TEST VALUES -->向表中插入数据
(1,100),
(2,200),
(3,300),
(4,400),
(5,500);
GO
SELECT * FROM TEST -->表的结构如下
/*
id num
1 100
2 200
3 300
4 400
5 500
*/
-------------------开始查询------------------
SELECT id,SUM(num1+num2+num3) AS num_sum
FROM
(
SELECT A.id,A.num AS num1,B.num AS num2,C.num AS num3
FROM TEST AS A
JOIN TEST AS B
ON A.id = B.id - 1
JOIN TEST AS C
ON A.id = C.id - 2
) AS T
GROUP BY id
-------------------运行结果------------------
/*
id num_sum
----------- -----------
1 600
2 900
3 1200
(3 行受影响)
*/
[/code] |
|