如果一个或多个扩展为真,如何按标志对 parent/child 记录进行分组,并折叠为标志为真的组合的单个记录?

How to group parent/child records by flag and collapse to a single record for the combo where the flag is true if one or more expanded was true?

抱歉标题太长,很难描述我想做什么。正如您将在下面看到的那样,它很容易理解,但很难概括为标题。

我查询 returns 以下数据:

| ParentID | ChildID | Flag |
| 100      | 1       | 0    |
| 100      | 1       | 1    |
| 100      | 2       | 0    |
| 100      | 2       | 0    |
| 200      | 1       | 1    |
| 200      | 1       | 1    |

标志栏将只有 1 或 0。 我需要过滤结果,以便每个 parent/child 组合只有一行。 如果上面的完整结果集中有一个或多个记录,则标志应为 1,其中 parent/child 组合为 1,否则应为零。

所以如果应用到上面的结果将是:

| ParentID | ChildID | Flag |
| 100      | 1       | 1    |
| 100      | 2       | 0    |
| 200      | 1       | 1    |

我只使用 ChildID 和 Flag 列:

DECLARE @InMemoryResultsFirstPass AS TABLE (ChildID Integer, Flag Integer)
DECLARE @InMemoryResultsRecs AS TABLE (ChildID Integer, Flag Integer)

INSERT INTO @InMemoryResultsFirstPass
      SELECT 1 ChildID, 0 Flag
UNION SELECT 1 ChildID, 1 Flag
UNION SELECT 2 ChildID, 0 Flag
UNION SELECT 2 ChildID, 0 Flag
UNION SELECT 1 ChildID, 1 Flag
UNION SELECT 1 ChildID, 1 Flag

select * from @InMemoryResultsFirstPass

INSERT INTO @InMemoryResultsRecs
SELECT DISTINCT 
    result.* 
FROM @InMemoryResultsFirstPass imr
    CROSS APPLY (
        SELECT TOP 1
            *
        FROM @InMemoryResultsFirstPass imrfp
        WHERE imrfp.ChildID = imr.ChildID
        ORDER BY imrfp.Flag DESC
    ) result

select * from @InMemoryResultsRecs

但是一旦我将它添加到 ParentID 列中,我就无法弄清楚如何执行此操作。我尝试了几种不同的方法,试图在 ParentID 上使用 GROUP BY 在 CROSS APPLY 中进行嵌套查询,但无论我尝试什么,我都会丢失 ParentID = 200 条记录:

DECLARE @InMemoryResultsFirstPass AS TABLE (ParentID Integer, ChildID Integer, Flag Integer)
DECLARE @InMemoryResultsRecs AS TABLE (ParentID Integer, ChildID Integer, Flag Integer)

INSERT INTO @InMemoryResultsFirstPass
      SELECT 100 ParentID, 1 ChildID, 0 Flag
UNION SELECT 100 ParentID, 1 ChildID, 1 Flag
UNION SELECT 100 ParentID, 2 ChildID, 0 Flag
UNION SELECT 100 ParentID, 2 ChildID, 0 Flag
UNION SELECT 200 ParentID, 1 ChildID, 1 Flag
UNION SELECT 200 ParentID, 1 ChildID, 1 Flag

select * from @InMemoryResultsFirstPass

INSERT INTO @InMemoryResultsRecs
SELECT DISTINCT 
    result.* 
FROM @InMemoryResultsFirstPass imr
    CROSS APPLY (
        SELECT TOP 1
            *
        FROM @InMemoryResultsFirstPass imrfp
        WHERE imrfp.ChildID = imr.ChildID
        ORDER BY imrfp.Flag DESC
    ) result

select * from @InMemoryResultsRecs

如有任何帮助,我们将不胜感激。

感谢您的宝贵时间。

其实我刚刚算出来的:

SELECT ParentID, ChildID, MAX(Flag) AS Flag
FROM @InMemoryResultsFirstPass
GROUP BY ParentID, ChildID
ORDER BY ParentID, ChildID

希望这对其他人有帮助:-)