You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据字段内容分配分组ID?含续行标识的数据分组需求

Solution to Create Grouped View with Continuation Rows

Got it, let's work through this problem step by step. The goal is to group rows where each group starts with a row whose key doesn't contain ..., followed by all subsequent rows where key includes ... (the continuation lines). We can use SQL window functions to assign unique group IDs easily—here's how:

Step-by-Step Explanation

First, we need to spot which rows kick off a new group: any row where key doesn't have ... is a group starter. Then, we'll accumulate a count of these starter rows as we traverse the table (ordered by linenr, since it's monotonically increasing) to get our unique group ID.

SQL Code to Create the View

Assuming your source table is named source_table, here's the view creation query:

CREATE VIEW grouped_records AS
SELECT
    linenr,
    key,
    -- Calculate unique group ID by counting group starters up to the current row
    SUM(CASE WHEN key NOT LIKE '%...%' THEN 1 ELSE 0 END) 
        OVER (ORDER BY linenr) AS group_id
FROM source_table;

Breakdown of the Code

  • The CASE statement tags group starter rows with 1 and continuation rows with 0.
  • The SUM() OVER (ORDER BY linenr) window function adds up these tags from the first row all the way to the current row. Every time we hit a new group starter, the sum increments—giving each group a unique ID (they don't have to be consecutive, which fits your requirement perfectly).

Example Output

If your source table looks like this:

linenrkey
1Customer A Details
4... Contact: Jane Doe
6... ID: 12345
9Customer B Details
10... Contact: John Smith

The view will return:

linenrkeygroup_id
1Customer A Details1
4... Contact: Jane Doe1
6... ID: 123451
9Customer B Details2
10... Contact: John Smith2

This works in most modern databases (PostgreSQL, MySQL 8+, SQL Server, etc.) that support window functions. If you're using an older database, feel free to ask for an adjusted approach!

内容的提问来源于stack exchange,提问作者John Frazer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:04:32