【发布时间】:2015-05-27 10:58:58
【问题描述】:
这是Sorting based on next and previous records in SQL的后续问题
但现在它变得有点复杂了,例如:
- 如果任何字母 1 匹配任何字母 2,我想更改排序,使字母与以下记录匹配。
- 如果未找到匹配项,则应按字母进行正常排序。
- ID 可能不成功,并且记录的顺序不正确。 [SQLFiddle Demo]
[Create script and SQL Fiddle demo]
create table Parent (
id [bigint] IDENTITY(1,2),
number bigint NOT NULL,
PRIMARY KEY (id)
)
GO
create table Child (
id [bigint] IDENTITY(1,2),
parentId BIGINT,
letter VARCHAR(1) NOT NULL,
PRIMARY KEY (id),
UNIQUE (parentId, Letter),
FOREIGN KEY (parentId) REFERENCES Parent(id)
)
GO
DECLARE @ParentIdentity BIGINT
INSERT Parent (number) VALUES (2)
SET @ParentIdentity = @@IDENTITY
INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'C')
INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'B')
INSERT Parent (number) VALUES (3)
SET @ParentIdentity = @@IDENTITY
INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'D')
INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'B')
INSERT Parent (number) VALUES (1)
SET @ParentIdentity = @@IDENTITY
INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'C')
INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'A')
GO
当前查询
目前我正在使用这个查询进行排序:
;WITH CTE AS
(
SELECT id,ParentID,letter,
ROW_NUMBER() OVER (ORDER BY ID) seq_id,
ROW_NUMBER() OVER (PARTITION BY parentId ORDER BY ID) first_element,
ROW_NUMBER() OVER (PARTITION BY parentId ORDER BY ID DESC) Last_element
FROM Child
), CTE2 AS
(
SELECT c1.id, c1.parentid, c1.letter, c2.parentid as c2parentid
FROM CTE c1
INNER JOIN CTE c2
ON c1.last_element = 1
AND c2.first_element = 1
AND c1.seq_id + 1 = c2.seq_id
), CTE3 AS
(
SELECT C.parentid, C.id
FROM CTE2
INNER JOIN child C ON CTE2.c2parentid = C.parentid
AND C.letter = CTE2.letter
)
SELECT P.number, C.letter
FROM Child C
JOIN Parent P ON C.parentId = P.id
LEFT JOIN CTE3 ON CTE3.id = C.id
ORDER BY P.number, ISNULL(CTE3.id,0) DESC, C.letter
当前结果集
number letter
-------------------- ------
1 A
1 C
2 B
2 C
3 B
3 D
预期结果集
为了澄清我真正想做的事情,这里是预期的结果集:
number letter
-------------------- ------
1 A
1 C
2 C
2 B
3 B
3 D
其他要求和问题
- 它必须在 SQL Server 2005 中工作。
- 有一个场景,每个数字使用 3 个字母,如果它只使用最佳匹配,我很高兴。
谁能指出我如何处理这种情况的正确方向?
【问题讨论】:
-
这在 SQL Server 2005 中将很难做到,因为对于给定的数字,您无法先验确定结果的顺序。你本质上是一个分层(递归)问题。
-
最好澄清一下“数字 1 的最后一个字母”实际上是指“数字 1 的最大字母值”,而不是基于
Child的最后一个id1人桌 -
@ughai 我实际上并不关心最大字母值。匹配的字母是我关心的,假设我们有:
1A 1C | 2B 2A。我想要1C 1A | 2A 2B的结果。我不知道如何在需求中描述这个 -
所以你的意思是任何字母 1 匹配任何字母 2
-
@Ughai 我更新了我的答案。
标签: sql sql-server sql-server-2005 sql-order-by