假设我有一个带有当前ID的表。
CREATE TABLE F
(
id int,
s char
)
INSERT INTO F VALUES(10)
和另一个带有行的表,这些行可以替换id或更新某些内容。
CREATE TABLE M
(
id int,
old_id int,
new_id int,
type char,
s char,
d date
)
类型在哪里指示它是替换id还是更新s。
INSERT INTO dbo.M (id, old_id, new_id, type, d, s)
VALUES
(2, 20,NULL,'U', '2018-01-01', 'a'),
(3, 10,20, 'R', '2018-01-01', NULL),
(4, 10,NULL,'U', '2018-01-01', 'b'),
(5, 20,NULL,'U', '2018-01-01', 'c'),
(6, 30,NULL,'U', '2018-01-01', 'd'),
(7, 20,30, 'R', '2018-01-01', NULL),
(8, 30,NULL,'U', '2018-01-01', 'e'),
(9, 40,NULL,'U', '2018-01-01', 'f')
如果我要对行进行排序,以便首先出现与F中的ID相匹配的“ U”,然后是与ID相匹配的“ R”,则接下来的行应按每个“ R”设置的ID进行排序。 / p>
所以顺序是4、3、2、5、7、8或4、3、5、2、7、8
答案 0 :(得分:4)
您将需要递归:
CREATE TABLE f(id int, s char);
INSERT INTO f(id) VALUES
(10);
CREATE TABLE m(id int, old_id int, new_id int, type char, s char, d date);
INSERT INTO m (id, old_id, new_id, type, d, s) VALUES
(2, 20, NULL, 'U', '2018-01-01', 'a'),
(3, 10, 20, 'R', '2018-01-01', NULL),
(4, 10, NULL, 'U', '2018-01-01', 'b'),
(5, 20, NULL, 'U', '2018-01-01', 'c'),
(6, 30, NULL, 'U', '2018-01-01', 'd'),
(7, 20, 30, 'R', '2018-01-01', NULL),
(8, 30, NULL, 'U', '2018-01-01', 'e'),
(9, 40, NULL, 'U', '2018-01-01', 'f');
WITH cte AS (
SELECT *, 1 AS lvl
FROM m AS base
WHERE old_id = (SELECT id FROM f)
UNION ALL
SELECT curr.*, lvl + 1
FROM m AS curr
INNER JOIN cte AS prev ON prev.type = 'R' AND curr.old_id = prev.new_id
)
SELECT *
FROM cte
ORDER BY lvl, CASE type WHEN 'U' THEN 1 WHEN 'R' THEN 2 END
结果:
| id | old_id | new_id | type | s | d | lvl |
|----|--------|--------|------|---|------------|-----|
| 4 | 10 | | U | b | 01/01/2018 | 1 |
| 3 | 10 | 20 | R | | 01/01/2018 | 1 |
| 2 | 20 | | U | a | 01/01/2018 | 2 |
| 5 | 20 | | U | c | 01/01/2018 | 2 |
| 7 | 20 | 30 | R | | 01/01/2018 | 2 |
| 6 | 30 | | U | d | 01/01/2018 | 3 |
| 8 | 30 | | U | e | 01/01/2018 | 3 |
R
行以获取新ID,然后从主表中选择旧ID =新ID的行