您假设句子是由升序的 id 编号形成的。这真是个坏主意。
此查询应为您提供有关断句的信息。(用真实的表名替换“T”。)
SELECT
Break1.Id as BreakId,
COALESCE(MAX(Break2.Id), 0) as PreviousBreakId,
COALESCE(COUNT(Break2.Id), 0) + 1 as BreakNumber
FROM
(SELECT Id FROM T WHERE Word LIKE '%.') as Break1,
(SELECT Id FROM T WHERE Word LIKE '%.') as Break2
WHERE Break2.Id < Break1.Id
GROUP BY Break1.Id
以下是在 UPDATE 中使用它的方法。
UPDATE T
SET SentenceNum = (
SELECT B.BreakNumber
FROM
(
SELECT
Break1.Id as BreakId,
COALESCE(MAX(Break2.Id), 0) as PreviousBreakId,
COALESCE(COUNT(Break2.Id), 0) + 1 as BreakNumber
FROM
(SELECT Id FROM T WHERE Word LIKE '%.') as Break1,
(SELECT Id FROM T WHERE Word LIKE '%.') as Break2
WHERE
Break2.Id < Break1.Id
GROUP BY Break1.Id
) as B
WHERE T.Id >= B.PreviousBreak AND T.Id < B.BreakId
)
我提供教育价值的查询,但我不能宽恕基于您的信息的方法。
编辑
我的原始版本的第一句话有问题,因为基本上逻辑会查找不存在的前句中断。@cravoori 的解决方案通过左连接来处理这个问题。这是一个与我自己的答案相同的工作版本,它返回完整的单词列表而不是中断。除了交叉连接和虚拟零行之外,本质上是相同的。
SELECT T.Id, MIN(T.Word) as Word, COUNT(Breaks.Id) as SentenceNumber
FROM T, (SELECT 0 as Id UNION ALL SELECT Id FROM T WHERE Word LIKE '%.') as Breaks
WHERE Breaks.Id < T.Id
GROUP BY T.Id;