包含列更改的 SQL 汇总

问题描述 投票:0回答:1

我遇到了一个问题,希望得到一些帮助。 例如我有一张桌子:

团体 部分
A 01 01 10
A 01 11 15
A 01 18 18
A 01 19 25
A 02 26 30
A 02 31 32
A 01 33 40
A 01 41 41

通过使用上面的表格,我想创建另一个表格(下面的示例),因此每次在

[Section]
更改之前,我都希望获得
MIN(Low)
MAX(High)

团体 部分
A 01 01 25
A 02 24 32
A 01 33 41
sql sql-server
1个回答
0
投票
Steps:
Identify Changes in Section: You need to track where the Section value changes. This can be achieved using window functions or by manually comparing the Section value in each row with the previous row.

Group the Data: Once you've identified the changes in the Section, you can group the data accordingly, aggregating Low and High values for each group.




>    WITH SectionGroups AS (
>         SELECT
>             Group,
>             Section,
>             Low,
>             High,
>            
>             SUM(CASE WHEN Section != LAG(Section) OVER (PARTITION BY Group ORDER BY Section, Low) THEN 1 ELSE 0 END) 
>             OVER (PARTITION BY Group ORDER BY Section, Low) AS GroupChange
>         FROM your_table
>     )
>     
>     SELECT
>         Group,
>         Section,
>         MIN(Low) AS Low,
>         MAX(High) AS High
>     FROM SectionGroups
>     GROUP BY Group, Section, GroupChange
>     ORDER BY Group, MIN(Low);

**Explanation**:

**LAG(Section):** This function compares the current row’s Section value with the previous row’s Section value.

**SUM(... OVER):** This part creates a "GroupChange" column that increments each time there’s a change in the Section. The SUM(CASE WHEN ...) logic works by checking if the current Section is different from the previous one. If it is, a new group is formed, otherwise, it continues with the same group.

**MIN(Low) and MAX(High):** Once the groups are identified, you can calculate the minimum Low and maximum High for each group.

GROUP BY: The final aggregation groups the results by Group, Section, and GroupChange to get the desired outcome.

**Expected Output:**
The result would look like this:

    Group   Section Low High
    A   01  01  25
    A   02  24  32
    A   01  33  41

This approach gives you the desired behavior where the Low is the minimum of the current section and the High is the maximum, while handling changes in the section properly.
© www.soinside.com 2019 - 2024. All rights reserved.