|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
[code=sql]USE tempdb
IF OBJECT_ID('TEST1') IS NOT NULL
DROP TABLE TEST1;
GO
CREATE TABLE TEST1
(
name char(1),num int,sdate date,id varchar(10)
);
GO
IF OBJECT_ID('TEST2') IS NOT NULL
DROP TABLE TEST2;
GO
CREATE TABLE TEST2
(
name char(1),num int,sdate date,id varchar(10)
);
GO
INSERT INTO TEST1 VALUES
('a',1,'2012-4-2','0011223'),
('b',2,'2012-5-2','0011224'),
('c',1,'2012-6-2','0011225'),
('a',1,'2012-7-2','0011226'),
('b',3,'2012-8-2','0011227'),
('c',5,'2012-9-2','0011228');
GO
INSERT INTO TEST2 VALUES
('a',1,'2012-4-2','0011223'),
('b',2,'2012-5-2','0011224'),
('c',1,'2012-6-2','0011225'),
('a',1,'2012-7-2','0011226'),
('c',5,'2012-9-2','0011228');
GO
-------------------------------------
SELECT A.name,A.num,A.id,B.id AS id2
FROM
(
SELECT name,num,id,
(
SELECT SUM(1)
FROM TEST1
WHERE name=a.name
AND num=a.num
AND sdate<=a.sdate
) AS ranks
FROM TEST1 AS a
) AS A
INNER JOIN
(
SELECT name,num,id,
(
SELECT SUM(1)
FROM TEST2
WHERE name=a.name
AND num=a.num
AND sdate<=a.sdate
) AS ranks
FROM TEST2 AS a
) AS B
ON A.name=B.name
AND A.num=B.num
AND A.ranks=B.ranks
-------------------------------------
/*
name num id id2
---- ----------- ---------- ----------
a 1 0011223 0011223
b 2 0011224 0011224
c 1 0011225 0011225
a 1 0011226 0011226
c 5 0011228 0011228
(5 行受影响)
*/
[/code] |
|